问题描述
我正在尝试修改列表元素,并用新修改的元素替换原始元素.但是,我注意到所需的行为因我构造for循环的方式而异.例如:
I'm trying to modify list elements and replace the original element with the newly modified one. However, I've noticed that the desired behavior differs depending on how I construct my for loop. For example:
samples = ['The cat sat on the mat.', 'The dog at my homework.']
punctuation = ['\'', '\"', '?', '!', ',', '.']
for sample in samples:
sample = [character for character in sample if character not in punctuation]
sample = ''.join(sample)
print(samples)
for i in range(len(samples)):
samples[i] = [character for character in samples[i] if character not in punctuation]
samples[i] = ''.join(samples[i])
print(samples)
该程序输出:
['The cat sat on the mat.', 'The dog at my homework.']
['The cat sat on the mat', 'The dog at my homework']
第二个for循环是从句子中删除标点符号的所需输出,但是我很难理解为什么会发生这种情况.我已经在线搜索过,发现这个Quora答案有助于解释技术细节,但是我想知道是否不可能使用for循环的第一种方法来修改列表元素,并且是否必须求助于使用range
或enumerate
之类的功能来修改循环中的列表元素.
The second for loop is the desired output with the punctuation removed from the sentence, but I'm having trouble understanding why that happens. I've searched online and found this Quora answer to be helpful in explaining the technical details, but I'm wondering if it's impossible to modify list elements using the first method of for loops, and if I have to resort to using functions like range
or enumerate
to modify list elements within loops.
谢谢.
推荐答案
修改迭代器是不够的,
您还需要修改列表:
这篇关于如何在for循环中修改列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!