How do I concatenate two lists in Python?

前端 未结 25 1965
时光取名叫无心
时光取名叫无心 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 07:00

    With Python 3.3+ you can use yield from:

    listone = [1,2,3]
    listtwo = [4,5,6]
    
    def merge(l1, l2):
        yield from l1
        yield from l2
    
    >>> list(merge(listone, listtwo))
    [1, 2, 3, 4, 5, 6]
    

    Or, if you want to support an arbitrary number of iterators:

    def merge(*iters):
        for it in iters:
            yield from it
    
    >>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
    [1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]
    

提交回复
热议问题