【发布时间】:2022-01-12 01:34:15
【问题描述】:
我想读取一个以逗号分隔的值的文件,并计算这些值的频率(在 0 .. 8 的范围内):
1,1,1,1,1,2,0,0,0,0,0,1,2,3,4,7,7,8,0,0,0
此代码有效:
with open("data.txt") as file:
l = [int(s) for s in file.readline().strip().split(",")]
a1 = [l.count(i) for i in range(9)]
print(a1)
首先我读取文件,用逗号分割它,并将输入的字符串转换为整数,收集列表l 中的所有内容。但是,将相同的两个作业合并为一个会中断:
with open("data.txt") as file:
a2 = [[int(s) for s in file.readline().strip().split(",")].count(i) for i in range(9)]
print(a2)
$ python -i aa.py # both snippets from above in one file
[0, 162, 36, 27, 47, 28, 0, 0, 0]
Traceback (most recent call last):
File "aa.py", line 7, in <module>
a2 = [([int(s) for s in file.readline().strip().split(",")].count(i)) for i in range(9)]
File "aa.py", line 7, in <listcomp>
a2 = [([int(s) for s in file.readline().strip().split(",")].count(i)) for i in range(9)]
File "aa.py", line 7, in <listcomp>
a2 = [([int(s) for s in file.readline().strip().split(",")].count(i)) for i in range(9)]
ValueError: invalid literal for int() with base 10: ''
P.S.:我知道我可能会使用 collections.Counter 并且 strip() 在这里可能不是必需的,但这并不能解释为什么我不能将这两个作业合二为一。
【问题讨论】:
-
内部理解被评估了 9 次,但在第一次评估时耗尽了文件对象。
标签: python python-3.x list-comprehension