简体   繁体   中英

Count occurances of a specific value in columns of list of list in python

I have a list as following:

[[1,0,1,3],
 [2,0,1,3],
 [2,3,0,2]]

I would like a count of appearance of 3 in each 3 as a list: ((0,0),(1,1),(2,0),(3,2))

What is the best to do this? Do I need to transpose and then use list comprehension?

You don't need to transpose, just keep a helper dictionary with counters:

m = [[1, 0, 1, 3], [2, 0, 1, 3], [2, 3, 0, 2]]

counters = {}

for j in range(len(m)):
    for i in range(len(m[j])):
        counters.setdefault(i, 0)
        counters[i] += m[j][i] == 3

print(tuple(counters.items()))

Prints:

((0, 0), (1, 1), (2, 0), (3, 2))

Using dataframes

import numpy as np
import pandas as pd


df = pd.DataFrame([[1,0,1,3],
 [2,0,1,3],
 [2,3,0,2]])

print((df==3).sum().sum())
3

There are 3 elements equals to 3.

Took some time. I'm a bit rusty with comprehensions. Thanks for a nice exercise.

m = [[1, 0, 1, 3], 
     [2, 0, 1, 3], 
     [2, 3, 0, 2]]

result = list([x, list(m[y][x] for y in range(3)).count(3)] for x in range(4))

print(result)

Will this work?

from collections import Counter
counter = Counter()
[counter.update(x) for x in ip_]
print(tuple(counter.items()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM