連線和合並列表

  1. 連線 list1list2 的最簡單方法

    merged = list1 + list2
    
  2. zip 返回一個元組列表,其中第 i 個元組包含來自每個引數序列或迭代的第 i 個元素:

    alist = ['a1', 'a2', 'a3']
    blist = ['b1', 'b2', 'b3']
    
    for a, b in zip(alist, blist):
        print(a, b)
    
    # Output:
    # a1 b1
    # a2 b2
    # a3 b3
    

    如果列表具有不同的長度,則結果將僅包括與最短的元素一樣多的元素:

    alist = ['a1', 'a2', 'a3']
    blist = ['b1', 'b2', 'b3', 'b4']
    for a, b in zip(alist, blist):
        print(a, b)
    
    # Output:
    # a1 b1
    # a2 b2
    # a3 b3
    
    alist = []
    len(list(zip(alist, blist)))
    
    # Output:
    # 0
    

    對於使用 Nones 的長度不等的填充列表,使用 itertools.zip_longest(Python 2 中的 itertools.izip_longest

    alist = ['a1', 'a2', 'a3']
    blist = ['b1']
    clist = ['c1', 'c2', 'c3', 'c4']
    
    for a,b,c in itertools.zip_longest(alist, blist, clist):
        print(a, b, c)
    
    # Output: 
    # a1 b1 c1
    # a2 None c2
    # a3 None c3
    # None None c4
    
  3. 插入特定索引值:

     alist = [123, 'xyz', 'zara', 'abc']
     alist.insert(3, [2009])
     print("Final List :", alist)
    

    輸出:

     Final List : [123, 'xyz', 'zara', 2009, 'abc']