Python for循环,修改了迭代列表

时间:2016-08-07 20:40:20

标签: python

我有这个.txt文件:

king james version of the bible   
the first book of moses  called genesis

我使用python脚本来统计.txt文件,将文件读入列表final_list,然后执行此代码(更长脚本的一部分):

for word in final_list:
    output_list.append((word,final_list.count(word)))

    final_list[:] = [x for x in final_list if x != word]
    #DEBUGGING
    print(len(final_list))
    print(final_list)

我的问题是我的一些列表没有被for循环使用,我怀疑从输出中查看:

12
['james', 'version', 'of', 'the', 'bible', 'the', 'first', 'book', 'of', 'moses', 'called', 'genesis']
11
['james', 'of', 'the', 'bible', 'the', 'first', 'book', 'of', 'moses', 'called', 'genesis']
9
['james', 'of', 'bible', 'first', 'book', 'of', 'moses', 'called', 'genesis']
8
['james', 'of', 'bible', 'book', 'of', 'moses', 'called', 'genesis']
6
['james', 'bible', 'book', 'moses', 'called', 'genesis']
5
['james', 'bible', 'book', 'moses', 'called']

这让我想知道python for循环实际上是如何工作的。

2 个答案:

答案 0 :(得分:2)

您不应该修改您在for循环中迭代的列表。否则你会得到这种奇怪的行为。您最好使用final_list的副本:

<% if (typeof selectedMake !== 'undefined') { %>

答案 1 :(得分:1)

麻烦的是你正在修改列表。在第一次迭代之后,Python的迭代器停止查看列表中的“位置0”并移动到“位置1”。您最初删除了位置0(king)中的元素,因此以前位于位置1(james)的元素现在位于位置0,这意味着当Python查看位置中的元素时1,它看到最初位于第2位的元素(version)。

最后,Python的迭代器已经移动到超出列表末尾的位置,因此它以您认为不成熟的方式退出,即使这正是您要求它执行的操作。