如何删除列表中的额外解析字符?

时间:2013-06-26 22:21:16

标签: python list

我有以下列表清单:

animals = [('dog', 'cat'), ('mouse', 'bird')]

我想将其缩小为:

animals = ['dog', 'cat', 'mouse', 'bird']

有一个更简单的方法来获得上面的结果而不是做这样的事情:

animals = [('dog', 'cat'), ('mouse', 'bird')]

final = []
for a in animals:
    final.append(a[0])
    final.append(a[1])
print final

1 个答案:

答案 0 :(得分:10)

您可以使用itertools.chain.from_iterable

>>> from itertools import chain
>>> list(chain.from_iterable(animals))
['dog', 'cat', 'mouse', 'bird']

或嵌套list comprehension

>>> [anim for item in animals for anim in item]
['dog', 'cat', 'mouse', 'bird']

对于小名单,请使用列表推导版本,否则使用itertools.chain.from_iterable

>>> animals = [('dog', 'cat'), ('mouse', 'bird')]
>>> %timeit list(chain.from_iterable(animals))
100000 loops, best of 3: 2.31 us per loop
>>> %timeit [anim for item in animals for anim in item]
1000000 loops, best of 3: 1.13 us per loop

>>> animals = [('dog', 'cat'), ('mouse', 'bird')]*100
>>> %timeit list(chain.from_iterable(animals))
10000 loops, best of 3: 31.5 us per loop
>>> %timeit [anim for item in animals for anim in item]
10000 loops, best of 3: 73.7 us per loop

>>> animals = [('dog', 'cat'), ('mouse', 'bird')]*1000
>>> %timeit list(chain.from_iterable(animals))
1000 loops, best of 3: 296 us per loop
>>> %timeit [anim for item in animals for anim in item]
1000 loops, best of 3: 733 us per loop