检查列表列表中是否存在项目的最佳方法是什么?

时间:2014-11-13 06:04:14

标签: python list python-3.x

我有这样的示例列表:

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

现在,我检查它是否有这样的空字符串:

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

print(has_empty)

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

5 个答案:

答案 0 :(得分:14)

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

>>> 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

答案 1 :(得分:2)

您可以使用anymapchain的组合:

In [19]: example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]

In [20]: import operator, itertools

In [21]: any(map(operator.not_, itertools.chain(*example_list)))
Out[21]: True

In [22]: example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['not empty', 'gg']]

In [23]: any(map(operator.not_, itertools.chain(*example_list)))
Out[23]: False

答案 2 :(得分:2)

只需将整个列表转换为字符串,然后检查是否存在空字符串,即''""

>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
>>> any(empty in str(example_list) for empty in ("''", '""'))
True
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], [ 'gg', '\'']]
>>> any(empty in str(example_list) for empty in ("''", '""'))
False

请注意,这不适用于作为字符串本身一部分的空字符串的列表 - 示例'hello "" world'

另一种方法可能是压扁字典并检查其中是否存在空字符串

>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['gg', 'hello "" world']]
>>> '' in [item for sublist in example_list for item in sublist]
False
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg', 'hello "" world']]
>>> '' in [item for sublist in example_list for item in sublist]
True

答案 3 :(得分:1)

使用maplambda

>>> def check_empty(l):
...     k=map(lambda x: '' in x and True,l)
...     for x in k:
...         if x==True:
...             return True
...     return False
... 
>>> check_empty(example_list)
False
>>> example_list
[['aaa'], ['fff', 'gg'], ['ff'], ['gg', 'hello "" world']]
>>> example_list = [['aaa'], ['fff', 'gg',''], ['ff'], ['gg', 'hello "" world']]
>>> check_empty(example_list)
True

答案 4 :(得分:0)

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

has_empty = False

for list in example_list:

    if '' in list:
        has_empty = True
print(has_empty)