Possible to append multiple lists at once? (Python

2020-02-24 11:10发布

I have a bunch of lists I want to append to a single list that is sort of the "main" list in a program I'm trying to write. Is there a way to do this in one line of code rather than like 10? I'm a beginner so I have no idea...

For a better picture of my question, what if I had these lists:

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

And want to append y and z to x. Instead of doing:

x.append(y)
x.append(z)

Is there a way to do this in one line of code? I already tried:

x.append(y, z)

And it wont work.

7条回答
在下西门庆
2楼-- · 2020-02-24 12:02

equivalent to above answer, but sufficiently different to be worth a mention:

my_map = {
   'foo': ['a', 1, 2],
   'bar': ['b', '2', 'c'],
   'baz': ['d', 'e', 'f'],
} 
list(itertools.chain(*my_map.values()))
['d', 'e', 'f', 'a', 1, 2, 'b', '2', 'c']

in the above expression, * is important for groking result as args to chain, this is same as prior chain(x,y,z). Also, note the result is hash-ordered.

查看更多
登录 后发表回答