user9410826
user9410826

Reputation:

How to return a count of values in a list of lists

I'm trying to return the number of values that are in each list, which are housed in a bigger list.

l = [(32, -59), (33, -58)], 
    [(33, -58), (28, 17), (27, 81)], 
    [(33, 28), (95, 49)], 
    [(76, 9), (33, 4)]

I have tried to use (sum(x.count('value') for x in l)) but this just returns the count of a single value.

I'm hoping to return:

2,3,2,2

I'm not too fussed what format it's in. Although, I'll eventually convert it to a df:

    1  2  3  4
 0  2  3  2  2

Upvotes: 2

Views: 539

Answers (4)

Aaditya Ura
Aaditya Ura

Reputation: 12689

You can map :

l = [[(32, -59), (33, -58)],
    [(33, -58), (28, 17), (27, 81)],
    [(33, 28), (95, 49)],
    [(76, 9), (33, 4)]]


print(list(map(len,l)))

output:

[2, 3, 2, 2]

Upvotes: 0

Dadep
Dadep

Reputation: 2788

you have a very simple solution using len() :

>>> l = [[(32, -59), (33, -58)], 
...     [(33, -58), (28, 17), (27, 81)], 
...     [(33, 28), (95, 49)], 
...     [(33, 28), (95, 78)]]
>>> lengths=[len(a) for a in l]
>>> lengths
[2, 3, 2, 2]

Upvotes: 4

Rakesh
Rakesh

Reputation: 82805

You need to use len to get the size of an array.

Ex:

l = [[(32, -59), (33, -58)], 
    [(33, -58), (28, 17), (27, 81)], 
    [(33, 28), (95, 49)], 
    [(76, 9), (33, 4)]]

print( [len(i) for i in l] )

Output:

[2, 3, 2, 2]

Upvotes: 1

Taohidul Islam
Taohidul Islam

Reputation: 5424

Just use lenfunction:

l = [[(32, -59), (33, -58)],
    [(33, -58), (28, 17), (27, 81)], 
    [(33, 28), (95, 49)], 
    [(76, 9), (33, 4)]]
for i in l:
    print(len(i))

output:

2
3
2
2

Upvotes: 1

Related Questions