Python zip()函数不起作用
问题描述:
我是Stack Overflow和Python的新手。 我想通过索引替换列表中的项目,并且当我运行此代码时只有第一个实例是替换。Python zip()函数不起作用
word = "DRIPPING"
letter = "P"
checkList = [" _ "] * len(word)
letterLocation=[3,4]
for (index, replacement) in zip(letterLocation, letter):
checkList[index] = replacement
print(checkList)
返回[' _ ', ' _ ', ' _ ', 'P', ' _ ', ' _ ', ' _ ', ' _ ']
任何帮助将是非常欢迎的。
答
zip
需要两个或更多的迭代器,并生成元组,每个迭代元包含一个元素,直到其中一个迭代器耗尽。
由于letter
只包含一个字符,zip
将因此仅发射单元组:
>>> list(zip(checkList,letter))
[(' _ ', 'P')]
你不需要zip
在这里,你可以简单地在checkList
迭代,并指派letter
所有这些索引:
for index in letterLocation: # look ma, no zip
checkList[index] = letter
+0
谢谢威廉。你是明星!请相信我过于复杂的事情。 – tadders
'zip'工作得很好,但是你使用'zip',你不应该使用'zip'。 –