我必须反转列表中长度大于 4 的每个单词。所以我尝试了:
for word in words:
if len(word) >= 5:
word = word[::-1]
但它没有用。但是这个:
for i in range(len(words)):
if len(words[i]) >= 5:
words[i] = words[i][::-1]
工作正常。有什么区别?
最佳答案
当您遍历列表时,Python 会创建对您的变量的引用(具有相同的 ID)。但是,这些不能就地编辑。例如检查这个:Can't modify list elements in a loop Python
考虑这个例子,希望它能帮助你:
words = ['abcdef','abc']
for ind,i in enumerate(words):
print('Loop {}'.format(ind))
i = i[::-1]
print('words equal {}'.format(words))
words[ind] = words[ind][::-1]
print('words equal {}'.format(words))
print()
返回:
Loop 0
words equal ['abcdef', 'abc'] # <--- after changing i (nothing changed)
words equal ['fedcba', 'abc'] # <--- after changing words[ind]
Loop 1
words equal ['fedcba', 'abc'] # <--- after changing i (nothing changed)
words equal ['fedcba', 'cba'] # <--- after changing words[ind]
在你的情况下
最简单的解决方案是使用列表理解。考虑一下:
rWords = [word[::-1] if len(word) >=5 else word for word in words]
关于python - 循环列表的两种方式 - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301666/