如何在Python中将多个值附加到列表

问题:如何在Python中将多个值附加到列表

我试图弄清楚如何在Python中将多个值附加到列表中。我知道有一些方法来做到这一点,如手动输入值,或在PUR追加操作for循环,或appendextend功能。

但是,我想知道是否还有更整洁的方法?也许某个软件包或功能?

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 put the append operation in a for loop, or the append and extend functions.

However, I wonder if there is a more neat way to do so? Maybe a certain package or function?


回答 0

您可以使用sequence方法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]

因此,您可以list.append()用来附加单个值,也list.extend()可以附加多个值。

You can use the sequence method list.extend to 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.

>>> 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 single value, and list.extend() to append multiple values.


回答 1

除了append函数以外,如果用“多个值”表示另一个列表,则可以像这样简单地将它们连接起来。

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]

Other than the append function, if by “multiple values” you mean another list, you can simply concatenate them like so.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]

回答 2

如果你看一下在官方的文档,你会看到下方appendextend。这就是您要寻找的。

itertools.chain如果您对高效的迭代感兴趣,而不是最终获得一个完全填充的数据结构,那也是很有用的。

If you take a look at the official docs, you’ll see right below append, extend. That’s what your looking for.

There’s also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.