每次在python中运行for循环时,都需要将i设置为零

2024-09-28 23:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在运行到26的第二个for循环中,每次从列表中删除一个项目时,我都希望它被设置回零,这样我就可以从一开始检查list1中所有字母表的集合中是否存在字母表。我尝试在for循环中的if语句中添加I=0,但它返回到其范围值,并且不存在重新设置为零。你知道吗

import string
def getAvailableLetters(lettersGuessed):
    str1 = string.ascii_lowercase
    list1 = [ ]
    list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    str3 = ""
    str4 = str3.join(lettersGuessed)

    for j in range(len(str4)):
       for i in range(26):
           if list1[i] == str4[i]:
           list1.remove(list1[i])


lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
getAvailableLetters(lettersGuessed)

Tags: 项目inimport列表forstringifrange
3条回答

请尝试以下操作:

import string

def getAvailableLetters(lettersGuessed):
    return sorted(set(string.ascii_lowercase) - set(lettersGuessed))

lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
getAvailableLetters(lettersGuessed)

你可以试试while loop,像这样:

i = 0
for j in range(len(str4)):
       while i < 26:
           if list1[i] == str4[i]:
               list1.remove(list1[i])
               i = 0
               continue
           i += 1

这样,您就可以实际地将循环中的icontinue的值从零更改为零。你知道吗

Python中的^{} loops有一个鲜为人知的else表达式,可以用来确定整个循环是否完成。这对于重新启动循环很有用。你知道吗

for j in range(…):
  while True:
    for i in range(26):
      if list1[i] == str4[i]:
        list1.remove(list1[i])
        break # Break out of the `for` loop to continue the `while`.
    else:
      # The `else` will not happen if we `break` in the `for` loop.
      break # Finished the `for` loop; Break out of the `while`.

相关问题 更多 >