我有一个数据集作为.txt文件,如下所示:
17900
66100
11300
94600
10600
28700
37800
我想从我的数据集中的每个数字中提取第一个数字,然后计算该数字作为我的数据集中的第一个数字出现的次数。我如何在python代码中解决这个问题?
使用名为data.txt
的数据文件。
from collections import Counter
with open('data.txt', 'r') as f:
firsts = [int(line[0]) for line in f.readlines()]
result = Counter(firsts)
print(result)
这将打印firstvalue: count
字典。
我不会在这里写代码,但提到了方法。
因为你有txt
文件,并想使用only
python
with open('sample.txt','r') as f:
val_store = {}
for line in f:
first_word = line[0]
if first_word not in val_store:
val_store[first_word] = 0
val_store[first_word]+=1
print(val_store)