-3

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.

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

Chris
  • 29,127
  • 3
  • 28
  • 51
  • 1
    Did you even try something or at least looked up the existing answers on Stack Overflow? – Sheldore Jun 24 '19 at 07:35
  • Hi, I looked up the forum, it seems that i cant find the right term for the search , as i imagine other people has asked this. i tried "nested count with conditions" but no luck. I built a code that counts 1 item type, and its working fine, now am looking to count when specific two items match. – Yahya Jaber Jun 24 '19 at 07:36
  • 1
    If you just copy paste the title of your question and add "python" to it and search, you will get so many answers. – Sheldore Jun 24 '19 at 07:37
  • but i want to count how many time two items appear, not 1 item. in my case, i need to count how many times 'a' & 'b' appeared – Yahya Jaber Jun 24 '19 at 07:41
  • Could you post what you have tried? At least the one you did that works for one element? – J...S Jun 24 '19 at 07:51

1 Answers1

0

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
Mark
  • 90,562
  • 7
  • 108
  • 148