将可迭代对象的所有元素添加到列表 [英] Add all elements of an iterable to list

查看:27
本文介绍了将可迭代对象的所有元素添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更简洁的方法来执行以下操作?

t = (1,2,3)t2 = (4,5)l.addAll(t)l.addAll(t2)打印 l # [1,2,3,4,5]

这是我迄今为止所尝试的:我宁愿避免在参数中传递列表.

def t_add(t,stuff):对于 t 中的 x:东西.append(x)

解决方案

使用 list.extend() 而不是 list.append() 添加来自一个可迭代到列表:

l.extend(t)l.extend(t2)

l.extend(t + t2)

甚至:

l += t + t2

其中 list.__iadd__(就地添加)在底层实现为 list.extend().

演示:

<预><代码>>>>l = []>>>t = (1,2,3)>>>t2 = (4,5)>>>l += t + t2>>>升[1, 2, 3, 4, 5]

但是,如果您只想创建一个 t + t2 列表,那么 list(t + t2) 将是到达那里的最短路径.

Is there a more concise way of doing the following?

t = (1,2,3)
t2 = (4,5)

l.addAll(t)
l.addAll(t2)
print l # [1,2,3,4,5]

This is what I have tried so far: I would prefer to avoid passing in the list in the parameters.

def t_add(t,stuff):
    for x in t:
        stuff.append(x)

解决方案

Use list.extend(), not list.append() to add all items from an iterable to a list:

l.extend(t)
l.extend(t2)

or

l.extend(t + t2)

or even:

l += t + t2

where list.__iadd__ (in-place add) is implemented as list.extend() under the hood.

Demo:

>>> l = []
>>> t = (1,2,3)
>>> t2 = (4,5)
>>> l += t + t2
>>> l
[1, 2, 3, 4, 5]

If, however, you just wanted to create a list of t + t2, then list(t + t2) would be the shortest path to get there.

这篇关于将可迭代对象的所有元素添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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