Possible to append multiple lists at once? (Python)

后端 未结 7 515
清歌不尽
清歌不尽 2020-12-29 02:41

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

7条回答
  •  攒了一身酷
    2020-12-29 03:16

    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.

提交回复
热议问题