Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sets in Python to find list membership?

Tags:

python

set

Given:

A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']]

I want to know if ['Yes', X, 'No'] exist within A, where X is anything I don't care.

I attempted:

valid = False
for n in A:
    if n[0] == 'Yes' and n[2] == 'No':
        valid = True

I know set() is useful in this type of situations. But how can this be done? Is this possible? Or is it better for me to stick with my original code?

like image 823
elwc Avatar asked Jan 28 '26 04:01

elwc


1 Answers

if you want check for existance you can just ['Yes', 'No'] in A:

In [1]: A = [['Yes', 'No'], ['Yes', 'Idontknow'], ['No', 'Yes'], ['No', 'Idontknow']]

In [2]: ['Yes', 'No'] in A
Out[2]: True

for the next case try:

In [3]: A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']]

In [4]: any(i[0]=='Yes' and i[2] == 'No' for i in A)
Out[4]: True

or you can possibly define a little func:

In [5]: def want_to_know(l,item):
   ...:     for i in l:
   ...:         if i[0] == item[0] and i[2] == item[2]:
   ...:             return True
   ...:     return False

In [6]: want_to_know(A,['Yes', 'xxx', 'No'])
Out[6]: True

any(i[0]=='Yes' and i[2] == 'No' for i in A*10000) actually seems to be the 10 times faster than than the conversion itself.

In [8]: %timeit any({(x[0],x[-1]) == ('Yes','No') for x in A*10000})
100 loops, best of 3: 14 ms per loop

In [9]: % timeit {tuple([x[0],x[-1]]) for x in A*10000}
10 loops, best of 3: 33.4 ms per loop

In [10]: %timeit any(i[0]=='Yes' and i[2] == 'No' for i in A*10000)
1000 loops, best of 3: 334 us per loop
like image 55
root Avatar answered Jan 29 '26 20:01

root