python - 我无法理解变量在 for 循环之前的作用
问题描述
我是 python 新手,我无法理解此 return 语句中“for”之前的变量的作用。我从这个问题中得到了这个代码的一个稍微修改过的版本
word = "boom"
def find_all(word, guess):
return [i for i, letter in enumerate(word) if letter == guess]
我知道该函数正在获取用户在单词“boom”中猜测的字母的每一次出现,为索引创建“i”,为枚举函数即将给出的值创建“字母”。最后说明如果单词中的字母等于单词中的猜测,就会发生这种情况。
什么是
i for i
不过呢?我在上面找不到任何东西,当我把它拿出来时,它会破坏代码。有没有办法在退货中写这个?
我修改后的代码然后在状态
board = "_" * len(word)
listed_board = list(board)
while board != word:
guess = input("Input a letter here ").lower()
if guess in word:
indices = find_all(word, guess)
print(indices)
listed_board = list(board)
for i in indices:
listed_board[i] = guess
board = "".join(listed_board)
print(listed_board)
我唯一不明白的另一部分是它在说什么
listed_board[i] = guess
这是在做什么?在listed_board上,此时它只是下划线,那么它是如何定位插入单词的正确位置并将其设置为用户猜测的呢?
感谢回复,谢谢!
解决方案
好的,这是您的代码的工作方式:
word = "boom"
def find_all(word, guess):
return [i for i, letter in enumerate(word) if letter == guess]
enumerate(word)
创建新的可迭代对象。来自的每个字母'boom'
都有自己的索引:[(0, 'b'), (1, 'o'), (2, 'o'), (3, 'm')]
. 现在for
循环遍历这个新对象,其中i
等于索引(来自上面列表的数字),并且letter
(变量)等于字母(来自列表的值)。因此,此函数将返回索引列表供您猜测。如果猜测相等'b'
,它将返回[0]
, 因为'o'
它将是[1, 2]
, for 'm'
, [3]
,否则此列表将为空。
更进一步:
while board != word:
guess = input("Input a letter here ").lower()
if guess in word:
indices = find_all(word, guess) # This will return all index where 'guess' is equal to letter from world. For example for word='foo', guess='o' it will return [1,2]
print(indices)
listed_board = list(board)
for i in indices: # for each index you have found:
listed_board[i] = guess # replace '_' with correct letter (guess)
board = "".join(listed_board) # change list to string
print(listed_board)
希望这段代码现在对你来说更明显。
推荐阅读
- bash - 从更大的列表中创建 4 个元素的所有组合
- android - 为什么某些应用程序风格中没有出现无崩溃统计信息?
- javascript - 当计算本身返回一个数字时,为什么我的得分获取器评估为 NaN?
- python - Python Pandas:使用相同的类别名称(在一列中)和 NaN(在另一列中)填充数据框
- php - PHP - RegEx - 查找开头和结尾相同的单词
- jsf - primefaces fileUpload 是否可以不显示文件详细信息但显示总进度条?
- objective-c - 为什么我不能在 NSMutable 字典中设置对象
- c++ - 尝试将我的单个 Visual Studio 2010 C++ 项目构建为 exe 和 DLL,而不是再次创建新项目
- python - 战舰游戏..数据库和存储玩家数据的一些问题
- google-apps-script - 时间戳有问题