Python 将可迭代对象的所有元素添加到列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20592808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:48:29  来源:igfitidea点击:

Add all elements of an iterable to list

pythonlisttuples

提问by Bartlomiej Lewandowski

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)

采纳答案by Martijn Pieters

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

使用list.extend(), 不要list.append()将可迭代对象中的所有项目添加到列表中:

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.

其中list.__iadd__(就地添加)list.extend()在引擎盖下实现。

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.

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

回答by thefourtheye

stuff.extendis what you want.

stuff.extend是你想要的。

t = [1,2,3]
t2 = [4,5]
t.extend(t2)
# [1, 2, 3, 4, 5]

Or you can do

或者你可以做

t += t2