python - csv 中第一位数字的数字频率,不导入

标签 python list csv dictionary frequency

我确实是 Python 的初学者,并且正在我的大学学习类(class)。如果您对这个问题有任何提示和建议,非常感谢。 我在编写 CSV 文件中第一个数字的频率代码时遇到了麻烦。 不允许进口。 例如,如果我有来自 CSV 的以下值, 我们必须计算出每个数字的第一个数字中出现了多少个 1,2,3,4,5,6,7,8,9,0, 等等,从 5.385686, 3665, 6942, 4053, 7726, 4601, 7302 第一个数字中有一个 3, 第一位数字有两个 4,第一位数字有一个 3 等等)

我删除了除号码和 之外的任何内容。从文件中。 (使用 Ascii 表校正器) 我尝试先将所有数据放入列表中并返回“5.385686”,但我不知道下一步该做什么..

预期输出:

[[26, 22, 28, 22, 16, 20, 31, 22, 13, 0]]

我仅显示 CSV 的一部分。

5.385686 3665 6942 4053 7726 4601 7302
11754.41657 7859 7002 1502 8754 449 472
800.1759341 2161 4958 3738 5105 1472 2487
1055.19226 7473 3713 4302 3174 6415 9094
1747.798453 2685 5343 3207 2137 1934 1101
2551.157404 3200 4655 2673 4270 821 330
480.7713868 1172 847 3683 9486 2258 6323
19018.97818 3678 5628 1171 7270 8333 2534
505.5652756 7222 4105 6529 169 307 3142
3759.276869 9649 1445 5944 8892 371 8307
4753 6737 906 5057 4401 8698 533
2790 5239 6392 8637 8785 1331 6848
3328 639 3519 7829 6796 3935 2893
6331 2986 6076 1085 7715 8241 5688
[[26, 22, 28, 22, 16, 20, 31, 22, 13, 0]]

这是我到目前为止得到的:

def filename():
file = open("sample_accounts.csv", "r")
filecsv = file.read()
filecsv = filecsv.lower()
a = []
b = [ ]

chlist = list(range(128))
del chlist[48:58]
del chlist[46]

for c in chlist:
filecsv = filecsv.replace(chr©," ")
a.append(chlist)

ftlist = filecsv.split()
greet = ftlist
a.append(ftlist)

for i in greet:
return greet[0]
# for i in greet:
# return greet[i]
#
# dic = {}
#
# for word in ftlist:
# dic[word] = dic.get(word,0) + 1
#
# # for item in dic: # **** *
# # print(item, dic[item])
# return greet




d = filename()

最佳答案

您可以通过字符串计算字典中每个数字的计数来做到这一点:

count = dict({})
with open('path to your file') as file:
    for line in file.readlines():
        for number in line.split(' '):
            number=number.strip()
            if len(number)<1:
                continue
            digit = number[0]
            if digit.isdigit():
                digit = int(digit)
                if digit in count:
                    count[digit] = count[digit]+1
                else:
                    count[digit] = 1
print(count.values())

输出:

[14, 11, 16, 12, 10, 11, 9, 11, 4]

关于python - csv 中第一位数字的数字频率,不导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62043386/

相关文章:

python - Cocotb 在门级仿真中使用泛型/参数

python - 为什么推荐使用 PyPI 使用 API token ?

Python:检查列表是否按顺序|列表末尾已定义

list - 使用通配符比较列表

JavaScript 代码导致 iOS Safari 崩溃

java - 如何使用java将.xls文件导入mysql数据库?

python - 学习曲线

python - 在 pandas 数据框中按列应用 seaborn 热图

python - 我正在尝试从 python 中的 .csv 文件中获取值并面临此错误

python - pd.read_csv 的小数问题