user8054212
user8054212

Reputation:

How display numbers from the first column and count the number of occurance?

I need to display data from the first column and count the number of appearance of every number:

file Path:

[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]

Code:

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

The expected results are: 162 152, 47, 116, 34, 199, 69, 34, ...

However, what my code gives me is: ['[162', '[152', '[', '[116', '[', '[199', '[', '[', ...

Upvotes: 1

Views: 37

Answers (2)

Prune
Prune

Reputation: 77837

As you read your input, you need to be a little more careful in processing each line. First, slice off the brackets with x[1:-1] (eliminate the end characters). Now you can split the line, grab the first field, and convert to an integer:

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

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

Output:

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

You can collapse this to a single statement if you want:

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

Upvotes: 1

Tim
Tim

Reputation: 2843

To just get the first element of each list:

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

To get counts of those values, use Python's Counter:

from collections import Counter

file="Path"
with open(file) as f:
    result = [x[0] for x in f.readlines()]
    print(Counter(result))

Upvotes: 0

Related Questions