递增列表值Python 3

时间:2015-05-04 11:41:46

标签: python

infile = open('numbers.txt','r')

c = 0
for i in infile:
    if int(i) > c:
        c = int(i)
hist = [0]*c

for i in infile:   #checking
    ii = int (i)-1
    hist[ii] += 1  # problem area seemingly

for i in range(c):
    print(str(i+1),':',end=' ')
    print(str(hist[i]))

上面代码的目的是打开number.txt,它有100个数字,全部在范围内(1,101),全部带有' \ n'两端的字符,并计算每个号码遇到的次数。

首先找到文件中的最大数字,然后使用最初设置为零的所有元素创建一个元素数等于文件中最大数字的列表。然后检查数字。文件中的所有数字都是整数。

如果文件中包含的最大数字是100,那么hist []列表最初有100个元素都是0。

在检查期间,如果遇到数字78,则具有索引[77]即his​​t [77]的元素从值0更新为1.如果再次遇到78,则hist [77]从1更改为2

这样,无论文件中出现什么数字,每个出现的数字都有一个计数器(也是不会出现的数字,但是最小的数字不会有计数器,但这不是问题)。

检查了正在打开的文件后,最初正确设置了hist列表,问题是当遇到相应的数字时,hist []列表的值没有增加。当我在结尾打印列表时,所有值仍为零。

我正在使用Python 3.4.3。脚本和' numbers.txt'在我的桌面上。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您正在循环文件两次,但没有将文件读取指针倒回到开头。在第二个循环之前添加file.seek()调用:

infile.seek(0)
for i in infile:   #checking

如果没有seek迭代超过infile,则不会产生任何进一步的行;你到达文件的末尾已经

你最好在这里使用collections.Counter() object

from collections import Counter

with open('numbers.txt','r') as infile:
    hist = Counter(int(line) for line in infile)

然后,您可以使用max(hist)获取最高统计数字,或使用Counter.most_common()方法检索最常见至最少的数字:

# In numerical order, setting missing numbers to 0
for i in range(1, max(hist) + 1):
    print('{}: {}'.format(i, hist.get(i, 0)))

# In most common to least order
# In numerical order
for number, count in hist.most_common():
    print('{}: {}'.format(number, count))