简体   繁体   中英

How Can I count the number of occurences for two items in a nested list

I have a nested list

a = [[1,'a','b'], [2,'c','d'], [3,'a','b']]

how can i count the number of occurrences that a & b appeared in the nested list?

in this case the answer shall be 2 times.

ps this is my first time post, so thanks for all the help.

You can test for inclusion in a list with

'a' in some_list

This will be true or false. You can make multiple tests with and (there are also some other ways that may be a little prettied):

'a' in some_list and 'b' in some_list

This will be true if both conditions are met. To do this for all the lists in your list you can use a list comprehension:

a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]

['a' in x and 'b' in x for x in a_list]

This will return a list of boolean values, one for each item in your list:

[True, False, True]

When treated like numbers python treats True as 1 and False as 0 . This means you can just sum that list to get you count and have a solution in one line:

a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]

sum(['a' in x and 'b' in x for x in a_list])
# 2

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