且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查列表中是否存在项目的***方法?

更新时间:2022-06-22 06:58:49

您可以使用 itertools.chain.from_iterable :

You can use itertools.chain.from_iterable:

>>> from itertools import chain
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
>>> '' in chain.from_iterable(example_list)
True

仅在内部列表更大(超过100个项目)的情况下,将any与生成器一起使用会比上面的示例更快,因为那样,使用Python for循环的速度代价将由快速补偿. in-操作:

Just in case if the inner lists are bigger(more than 100 items) then using any with a generator will be faster than the above example because then the speed penalty of using a Python for-loop is compensated by the fast in-operation:

>>> any('' in x for x in example_list)
True

时间比较:

>>> example_list = [['aaa']*1000, ['fff', 'gg']*1000, ['gg']*1000]*10000 + [['']*1000]
>>> %timeit '' in chain.from_iterable(example_list)
1 loops, best of 3: 706 ms per loop
>>> %timeit any('' in x for x in example_list)
1 loops, best of 3: 417 ms per loop

# With smaller inner lists for-loop makes `any()` version little slow

>>> example_list = [['aaa'], ['fff', 'gg'], ['gg', 'kk']]*10000 + [['']]
>>> %timeit '' in chain.from_iterable(example_list)
100 loops, best of 3: 2 ms per loop
>>> %timeit any('' in x for x in example_list)
100 loops, best of 3: 2.65 ms per loop