cruzz7oh7
cruzz7oh7

Reputation: 11

How can I count the number of times a specific number appears in list vertically in python 3?

I'm trying to count the number of times a specific number appears in serval lists vertically.

My code:

import csv
with open('Superheroes.csv', 'r') as csvfile:
first_line = csvfile.readline()
super_reader = csv.reader(csvfile, delimiter=',')
result = []
for vote in super_reader:
    vote.pop(0)
    result.append([int(x) if x else 0 for x in vote])

result = [vote.count(1) for i in zip(*result)]

print(result)

example picture

So from the example picture, say I wanted to know how many times the number 11 appeared in every column of all the lists. I would expect an output of [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 4, 2] Thanks

Upvotes: 0

Views: 60

Answers (1)

blhsing
blhsing

Reputation: 107115

You can use sum with a generator expression that outputs whether each item in a column matches the target number to perform the counting after transposing the rows into columns with zip:

def count(rows, num):
    return [sum(i == num for i in map(int, col)) for col in zip(*rows)]

so that given the content of test.csv as follows:

2,1,3
3,2,1
1,3,3
1,3,2

count(csv.reader(open('test.csv')), 3) would return:

[1, 2, 2]

Demo: https://repl.it/@blhsing/IllAffectionateQuarks#main.py

Upvotes: 1

Related Questions