如何将多个值附加到 Python 中的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20196159/
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
How to append multiple values to a list in Python
提问by ChangeMyName
I am trying to figure out how to append multiple values to a list in Python. I know there are few methods to do so, such as manually input the values, or pur the append operation in a forloop, or appendand extendfunctions.
我想弄清楚如何在 Python 中将多个值附加到列表中。我知道有一些方法来做到这一点,如手动输入值,或在PUR追加操作for循环,或append和extend功能。
However, I wonder if there is a more neat way to do so? Maybe a certain package or function?
但是,我想知道是否有更简洁的方法来做到这一点?也许某个包或功能?
采纳答案by poke
You can use the sequence method list.extendto extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
您可以使用序列方法list.extend通过来自任何类型的可迭代对象的多个值扩展列表,无论是另一个列表还是提供值序列的任何其他事物。
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()to append a singlevalue, and list.extend()to append multiplevalues.
因此,您可以使用list.append()附加单个值,也list.extend()可以附加多个值。
回答by slider
Other than the appendfunction, if by "multiple values" you mean another list, you can simply concatenate them like so.
除了append函数之外,如果“多个值”是指另一个列表,则可以像这样简单地连接它们。
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
回答by Silas Ray
If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.
如果您查看官方文档,您会在下面看到append, extend。这就是你要找的。
There's also itertools.chainif you are more interested in efficient iteration than ending up with a fully populated data structure.
还有itertools.chain,如果你更感兴趣的是高效的迭代比完全填充的数据结构结束了。

