简体   繁体   中英

How do I count occurrences of a specific element in a position in a list of lists?

For example,

a=[[a, 1], [b, 1], [1, 1]]

I want to find how many "1"s there are, but only those that are the second element in the nested lists. So it should give me 3, ignoring the "1" in the third list as it is the first element in the list.

Use collections.Counter subclass to count occurrences of any value:

import collections

a = [['a', 1], ['b', 1], [1, 1]]
counts = collections.Counter((l[1] for l in a))

print(counts[1])   # 3

You could just use a generator and sum() .

>>> a = [['a', 1], ['b', 1], [1, 1]]
>>> sum(ele[1] == 1 for ele in a)
3

你可以使用: -

[item for sub_list in a[1:] for item in sub_list].count(1) # 3

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