将您转换list
为set
第一个,因为它会将查找时间从 缩短O(n)
为O(1)
:
In [27]: A = [['Yes', 'No'], ['Yes', 'Idontknow'], ['No', 'Yes'], ['No', 'Idontknow']]
In [28]: s=set(tuple(map(tuple,A)))
In [29]: s
Out[29]: set([('Yes', 'No'), ('No', 'Idontknow'), ('Yes', 'Idontknow'), ('No', 'Yes')])
In [30]: ('Yes', 'No') in s
Out[30]: True
timeit
比较:
%timeit ['Yes', 'No'] in A
1000000 loops, best of 3: 504 ns per loop
%timeit ('Yes', 'No') in s
1000000 loops, best of 3: 442 ns per loop #winner
%timeit ['No', 'Idontknow'] in A
1000000 loops, best of 3: 861 ns per loop
%timeit ('No', 'Idontknow') in s
1000000 loops, best of 3: 461 ns per loop #winner
编辑:
如果您只对第一个和最后一个元素感兴趣:
In [69]: A = [['Yes', 'No'], ['Yes', 'Idontknow','hmmm'], ['No', 'Yes'], ['No', 'Idontknow']]
In [70]: s={tuple([x[0],x[-1]]) for x in A} # -1 or 2, change as per your requirement
#or set(tuple([x[0],x[-1]]) for x in A)
In [71]: s
Out[71]: set([('Yes', 'No'), ('Yes', 'hmmm'), ('No', 'Idontknow'), ('No', 'Yes')])
In [73]: ('Yes', 'hmmm') in s
Out[73]: True
timeit
比较any()
:
In [77]: %timeit ('Yes', 'hmmm') in s
1000000 loops, best of 3: 428 ns per loop #winner
In [78]: %timeit any(x[0]=="Yes" and x[-1]=="hmmm" for x in A)
100000 loops, best of 3: 2.87 us per loop