How do I concatenate two lists in Python?

前端 未结 25 1926
时光取名叫无心
时光取名叫无心 2020-11-21 06:18

How do I concatenate two lists in Python?

Example:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

Expected outcome:

>&g         


        
25条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:45

    This question directly asks about joining two lists. However it's pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists).

    I think the best option is to use list comprehensions:

    >>> a = [[1,2,3], [4,5,6], [7,8,9]]
    >>> [x for xs in a for x in xs]
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    You can create generators as well:

    >>> map(str, (x for xs in a for x in xs))
    ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    

    Old Answer

    Consider this more generic approach:

    a = [[1,2,3], [4,5,6], [7,8,9]]
    reduce(lambda c, x: c + x, a, [])
    

    Will output:

    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Note, this also works correctly when a is [] or [[1,2,3]].

    However, this can be done more efficiently with itertools:

    a = [[1,2,3], [4,5,6], [7,8,9]]
    list(itertools.chain(*a))
    

    If you don't need a list, but just an iterable, omit list().

    Update

    Alternative suggested by Patrick Collins in the comments could also work for you:

    sum(a, [])
    

提交回复
热议问题