计算数字显示为数据集中第一个数字的次数[关闭]

问题描述 投票:-5回答:3

我有一个数据集作为.txt文件,如下所示:

17900
66100
11300
94600
10600
28700
37800

我想从我的数据集中的每个数字中提取第一个数字,然后计算该数字作为我的数据集中的第一个数字出现的次数。我如何在python代码中解决这个问题?

python
3个回答
1
投票

使用名为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字典。


0
投票

我不会在这里写代码,但提到了方法。

  1. 使用open和readlines来解析文件中的行
  2. 初始化字典以用于跟踪计数
  3. 现在您有一个包含数字作为字符串的行列表
  4. 访问每一行的第一个元素并检查字典是否已经看到A.如果看到,则增加值B.如果是新的则将1赋值为值

-1
投票

因为你有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)
© www.soinside.com 2019 - 2024. All rights reserved.