检查列表中是否存在项目的最佳方法? [英] Best way to check if an item is present in a list of lists?

查看:61
本文介绍了检查列表中是否存在项目的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的示例列表:

example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]

现在,我检查它是否具有空字符串,如下所示:

Now, I check if it has empty string like this:

has_empty = False;
for list1 in example_list:
    for val1 in list1:
        if val1 == '':
            has_empty = True

print(has_empty)

这可以正常工作,因为它可以打印True,但是否正在寻找更多的pythonik方法?

This works OK as it prints True, but looking for more pythonik method?

推荐答案

您可以使用 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

这篇关于检查列表中是否存在项目的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆