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. One can do it in two steps using 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?
l1.extend([l2, [u,z]])
append
can only add one element to a list. extend
takes a list and adds all the elements in it to other list.
You can use extend
as follows:
l1.extend([l2,[u,z]])
Or just:
l1 + [l2] + [[u,z]]
You can use any of the following methods:
Method 1 :
>>> l1.extend([l2, [u,z]])
>>> l1
[['a', 'b'], [1, 2]]
append
: Appends object at end
extend
: Extends list by appending elements from the iterable
Method 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.