如何在Python中将多个值附加到列表 [英] How to append multiple values to a list in Python

查看:136
本文介绍了如何在Python中将多个值附加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在Python中将多个值附加到列表中.我知道很少有这样做的方法,例如手动输入值或在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 pur the append operation in a for loop, or appendand extend functions.

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

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

推荐答案

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

因此,您可以使用list.append()附加单个值,并使用list.extend()附加多个值.

So you can use list.append() to append a single value, and list.extend() to append multiple values.

这篇关于如何在Python中将多个值附加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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