zip
迭代遍历两个列表,或者构建一个字典对象
enumerate
输出索引值的迭代遍历输出
combinations
迭代列表组合
permutations
迭代列表组合排序
itertools.chain.from_iterable
将单个iterable的所有元素拼接输出
itertools.chain
链接可遍历对象
list1 = [1, 2, 3]
list2 = ['aa', 'bb', 'cc', 'dd']
for i, j in zip(list1, list2):
print(str(i) + j)
print(dict(zip(list1, list2)))
for x in combinations(list1, 3):
print(x)
print("------------------------")
for i in permutations(list1, 3):
print(i)
---------------------------------------------
#1aa
#2bb
#3cc
#{1: 'aa', 2: 'bb', 3: 'cc'}
#(1, 2, 3)
#------------------------
#(1, 2, 3)
#(1, 3, 2)
#(2, 1, 3)
#(2, 3, 1)
#(3, 1, 2)
#(3, 2, 1)
"""连接列表"""
import itertools
from itertools import chain
test = [[-1, -2], [30, 32], [23, 33]]
print(list(itertools.chain.from_iterable(test)))
#[-1, -2, 30, 32, 23, 33]
test = chain('ab', 'c', 'd')
print(list(test)) # #['a', 'b', 'c', 'd']
a = [1, 4]
b = [11, 42]
c = [14, 423]
print(sum((a, b, c), [])) # [1, 4, 11, 42, 14, 423]
列表的各种连接方式
# 1/itertools
from itertools import chain
list1 = [1, 3, 4]
list2 = [12, 23, 42]
list3 = [13, 33, 34]
# itertools.chain
print(list(chain(list1, list2, list3)))
# 解包
print([*list1, *list2, *list3])
# extend
# list1.extend(list2)
# print(list1)
# 推导式
# for i in
print([x for i in (list1, list2, list3) for x in i])
tuidaolist = []
for i in (list1, list2, list3):
for j in i:
tuidaolist.append(j)
print(tuidaolist)
# 使用heapq, 附带排序
from heapq import merge
print("使用heapq, 附带排序", list(merge(list1, list2, list3)))
# 使用魔术方法
print("使用魔术方法", list1.__add__(list2).__add__(list3))
# 魔术方法 + reduce
from functools import reduce
print("魔术方法 + reduce", reduce(list.__add__, (list1, list2, list3)))
# 使用yield from 可接一个可迭代对象,用于迭代并返回其中的每个元素
def merge(*lists):
for l in lists:
print("-----")
yield from l
print("--&---")
print(list(merge(list1, list2, list3)))
# 借用sum函数
print(sum((list1, list2, list3), []))