给定:
A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']]
我想知道 ['Yes', X, 'No'] 是否存在于 A 中,其中 X 是我不关心的任何东西.
I want to know if ['Yes', X, 'No'] exist within A, where X is anything I don't care.
我尝试过:
valid = False for n in A: if n[0] == 'Yes' and n[2] == 'No': valid = True我知道 set() 在这种情况下很有用.但是怎么做呢?这可能吗?还是坚持使用原始代码对我来说更好?
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?
推荐答案如果你想检查是否存在,你可以在 A 中['Yes', 'No']:
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对于下一个案例尝试:
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]: Trueany(i[0]=='Yes' and i[2] == 'No' for i in A*10000) 实际上似乎比转换快 10 倍自己.
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更多推荐
如何在 Python 中使用集合来查找列表成员资格?
发布评论