Add all elements of an iterable to list(将可迭代的所有元素添加到列表)
问题描述
是否有更简洁的方法来执行以下操作?
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)
推荐答案
使用 list.extend()
,而不是 list.append()
从一个可迭代到列表:
Use list.extend()
, not list.append()
to add all items from an iterable to a list:
l.extend(t)
l.extend(t2)
或
l.extend(t + t2)
甚至:
l += t + t2
其中 list.__iadd__
(就地添加)在底层实现为 list.extend()
.
where list.__iadd__
(in-place add) is implemented as list.extend()
under the hood.
演示:
>>> l = []
>>> t = (1,2,3)
>>> t2 = (4,5)
>>> l += t + t2
>>> l
[1, 2, 3, 4, 5]
但是,如果您只想创建一个 t + t2
列表,那么 list(t + t2)
将是到达那里的最短路径.
If, however, you just wanted to create a list of t + t2
, then list(t + t2)
would be the shortest path to get there.
这篇关于将可迭代的所有元素添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将可迭代的所有元素添加到列表


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01