python - 如何显示第一列的数字并统计出现的次数?

标签 python

我需要显示第一列的数据并统计每个数字出现的次数:

文件路径:

[162 164 168 177 189 190 195 254 255  52]
[152 190 195  74 254 164 249  90 151  52]
[ 47 126 254 152  74 195 164 151 189  52]
[116 120 149 164 152 151 195 189  21  52]
[ 34 195  59 199 252  38  82 189  21  52]
[199 164 151  59  82  38  21 189 227  52]
[ 69 170  38  34 177 153  21 189  52 227]
[ 34 107 177 149 118  21  69 189  52 227]
[ 51  88  75  59  38 107 177 189  52 227]
[109  38 149 112 118  51 177  52 189 227]
[ 89  25  75  59 177 170 107  52 189 227]
[244 107  59 170  88  56  89  52 189 227]
[ 30 183 107  59 170  88  56  52 189 227]

代码:

file="Path"
with open(file) as f:
    lines = f.readlines()
    result = []
    for x in lines:
        result.append(x.split(' ')[0])
    print(result)
    f.close()

预期结果为:162 152, 47, 116, 34, 199, 69, 34, ...

但是,我的代码给我的是: ['[162', '[152', '[', '[116', '[', '[199', '[', '[', ...

最佳答案

当您阅读输入时,您需要在处理每一行时更加小心。首先,用 x[1:-1] 切掉括号(消除结束字符)。 现在您可以拆分行,获取第一个字段,然后转换为整数:

with open("Path") as f:
    result = []

    for line in f.readlines():
        field1 = line[1:-1].split()[0]
        result.append(int(field1))
    print(result)

输出:

[162, 152, 47, 116, 34, 199, 69, 34, 51, 109, 89, 244, 30]

如果需要,您可以将其折叠为单个语句:

result = [int(line[1:-1].split()[0])
          for line in open("Path").readlines()]

关于python - 如何显示第一列的数字并统计出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53621586/

相关文章:

python - Pandas:列对象不可调用

python - 如何在一个单元格中包含 python 代码和 markdown

python - 实现一个 child 和 parent 可以互相引用的树

python 名称错误 : name 'file' is not defined in python 3. 5

python - 按时间间隔+聚合函数对 Pandas 进行分组

python - 为什么这条 python 行不是错误?

python - Python 中多个类的混淆矩阵

python - 我从 AutoEncoder tensorflow2.0 数据中按时间顺序得到了错误的数据

python - 如何将字典转换为 Python 中的字典列表?

javascript - 更新呈现的 Django 模板中的列表项