我有这样的示例列表:
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方法?
您可以使用itertools.chain.from_iterable:
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
>>> 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