I'd like to read in a file with comma-separated values, and count the frequencies of these values (which are in a range of 0 .. 8 inclusive):
1,1,1,1,1,2,0,0,0,0,0,1,2,3,4,7,7,8,0,0,0
This code works:
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)
First I read the file, split it by commas, and convert the string input in integers, collecting everything in the list l
. However, combining the same two assignments into a single one breaks:
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.: I am aware that I might use collections.Counter
and that strip()
might not be necessary here, but that doesn't explain why I can't combine the two assignments into one.