Possible to append multiple lists at once? (Python)

后端 未结 7 480
清歌不尽
清歌不尽 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:03

    You can use sum function with start value (empty list) indicated:

    a = sum([x, y, z], [])
    

    This is especially more suitable if you want to append an arbitrary number of lists.

    0 讨论(0)
  • 2020-12-29 03:04

    Extending my comment

    In [1]: x = [1, 2, 3]
    In [2]: y = [4, 5, 6]
    In [3]: z = [7, 8, 9]
    In [4]: from itertools import chain
    In [5]: print list(chain(x,y,z))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    0 讨论(0)
  • 2020-12-29 03:11

    To exactly replicate the effect of append, try the following function, simple and effective:

    a=[]
    def concats (lists):
        for i in lists:
            a==a.append(i)
    
    
    concats ([x,y,z])
    print(a)
    
    0 讨论(0)
  • 2020-12-29 03:15
    x.extend(y+z)
    

    should do what you want

    or

    x += y+z
    

    or even

    x = x+y+z
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 03:20

    In one line , it can be done in following ways

    x.extend(y+z)
    

    or

    x=x+y+z
    
    0 讨论(0)
提交回复
热议问题