为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除列表中的多余解析字符?

如何删除列表中的多余解析字符?

肥皂起泡泡 2021-03-30 12:13:52
我有以下列表列表: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 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

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


查看完整回答
反对 回复 2021-04-06
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信