[英]Python: how to simultaneously add two lists to a list?
Let's say I have a list 假设我有一个清单
l1 = []
another list 另一个清单
l2 = ['a','b']
and two variables 和两个变量
u = 1
z = 2
Now I would like to add l2 to l1 and the two variables as a list to l1 as well. 现在我想将l2和l1两个变量作为列表添加到l1中。 One can do it in two steps using append:
可以使用append分两步完成:
l1.append(l2)
l1.append(list((u,z)))
which gives me the desired output 这给了我想要的输出
[['a', 'b'], [1, 0]]
But something like 但有点像
l1.append(l2, list((u,z)))
does not work. 不起作用。 Is there a way to get the same output I obtain for the two steps in a nice oneliner ie can one simultaneously append a list by two lists?
有没有办法获得我在一个漂亮的oneliner中的两个步骤获得的相同输出,即可以同时通过两个列表附加列表?
l1.extend([l2, [u,z]])
append
can only add one element to a list. append
只能向列表中添加一个元素。 extend
takes a list and adds all the elements in it to other list. extend
接受一个列表并将其中的所有元素添加到其他列表中。
You can use extend
as follows: 您可以使用
extend
如下:
l1.extend([l2,[u,z]])
Or just: 要不就:
l1 + [l2] + [[u,z]]
You can use any of the following methods: 您可以使用以下任何方法:
Method 1 : 方法1:
>>> l1.extend([l2, [u,z]])
>>> l1
[['a', 'b'], [1, 2]]
append
: Appends object at end append
:在末尾追加对象
extend
: Extends list by appending elements from the iterable extend
:通过附加iterable中的元素来扩展列表
Method 2 : 方法2:
>>> l1 += [l2] + [[u, z]]
>>> l1
[['a', 'b'], [1, 2]]
通过创建生成器很简单
import itertools
for item in itertools.chain(listone, listtwo):
# do what you want to do with this merged list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.