How to combine logical gate NOT in lst.count((x, not y)) in Python

Viewed 94

I am trying to construct contingency table from a list of tuples. The list looks like this:

lst = [('a', 'bag'), ('a', 'bag'), ('a', 'bag'), ('a', 'cat'), ('a', 'pen'), ('that', 'house'), ('my', 'car'), ('that', 'bag'), ('this', 'bag')]

Given a tuple, say ('a', 'bag'), 4 things have to be worked out:

a = lst.count(('a', 'bag')) which is 3.

b is the count of all tuples where tuple[0] == 'a' and tuple[1] != 'bag', and it is 2: ('a', 'cat'), ('a', 'pen').

When I try

lst.count(('a', not 'bag')) I get 0, although it should be 2. -----1

c is the count of all the tuples where tuple[0] != 'a' and tuple[1] == 'bag'. In this case, ('that', 'bag'), ('this', 'bag'). But when I try

lst.count((not 'a', 'bag')) I get 0, although it should be 2. -----2

d is the count of all the tuples where tuple[0] !== 'a' and tuple[1] != 'bag and it can be easily obtained from len(lst) - a.

My question: Is there any way to combine logical gate not in lst.count((x, not y)) or lst.count((not x, y))? If not, could you suggest to me how I can work out b and c without loops, because the complexity is 2(N*N) which is quite expensive.

Your kind help is really appreciated!

3 Answers
Related