Python:打印迭代次数太多

时间:2015-07-10 19:10:04

标签: python arrays data-structures

我不太了解Python的一件事。当我创建一个数组,向它追加数据并尝试打印时,迭代会重复太多时间,例如:

with open("file.txt", "r") as fh1:
    array = []
        counter = 0
        for line in fh1:
            line = line.rstrip("\n")
            counter +=1
            array.append((line, counter))
            for line, counter in (array):
                print line, ":", counter

file.txt的:

 a
 b
...
 y
 z

脚本输出由于某种原因重复多次。我在构建的每个数组中都遇到此问题并尝试打印。我误会了什么吗?

1 个答案:

答案 0 :(得分:3)

由于for line, counter in (array):在另一个for循环

中的事实,它被多次打印

实际上它会为文件中的每一行打印,因为for循环遍历文件的行

with open("file.txt", "r") as fh1:
    array = []
    counter = 0
    for line in fh1:
        line = line.rstrip("\n")
        counter +=1
        array.append((line, counter))
for line, counter in (array):
    print line, ":", counter