Python合并和合并列表

示例

  1. 连接 list1和的最简单方法list2:

    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)

    # 输出:
    # 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)
    # 输出:
    # a1 b1
    # a2 b2
    # a3 b3
    alist = []
    len(list(zip(alist, blist)))
    # 输出:
    # 0

    对于长度不等长的填充列表,请使用Nones itertools.zip_longest(itertools.izip_longest在Python 2中)

    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)
    # 输出:
    # a1 b1 c1
    # a2无c2
    # a3无c3
    # 无无c4
  1. 插入到特定索引值:

     alist = [123, 'xyz', 'zara', 'abc']
    alist.insert(3, [2009])
    print("最终名单:", alist)

    输出:

     最终名单: [123, 'xyz', 'zara', 2009, 'abc']