连接和合并列表
-
连接
list1
和list2
的最简单方法 :merged = list1 + list2
-
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
对于使用
None
s 的长度不等的填充列表,使用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
-
插入特定索引值:
alist = [123, 'xyz', 'zara', 'abc'] alist.insert(3, [2009]) print("Final List :", alist)
输出:
Final List : [123, 'xyz', 'zara', 2009, 'abc']