welcome to my blog
问题:比如有两个列表, a=[1,2,3], b = [‘q’,‘w’], a和b元素的所有组合为[[1,‘q’], [1,‘w’],[2,‘q’], [2,‘w’],[3,‘q’], [4,‘w’]], 那么如果有多个列表, 该如何获取所有列表的组合呢?
方法一, 使用itertools模块
import itertools
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ['@@', '$$']
res = list(itertools.product(a, b, c))
print(res)
print(len(res))
'''
打印结果:
[[1, 'a', '@@'], [1, 'a', '$$'], [1, 'b', '@@'], [1, 'b', '$$'],
[1, 'c', '@@'], [1, 'c', '$$'], [1, 'd', '@@'], [1, 'd', '$$'],
[2, 'a', '@@'], [2, 'a', '$$'], [2, 'b', '@@'], [2, 'b', '$$'],
[2, 'c', '@@'], [2, 'c', '$$'], [2, 'd', '@@'], [2, 'd', '$$'],
[3, 'a', '@@'], [3, 'a', '$$'], [3, 'b', '@@'], [3, 'b', '$$'],
[3, 'c', '@@'], [3, 'c', '$$'], [3, 'd', '@@'], [3, 'd', '$$']]
24
'''
方法二,手动实现, 使用回溯法(深度优先遍历)
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ['@@', '$$']
# 主体函数
def combination(a, b, c):
config = [a, b, c]
res = []
tmp = []
dfs(res, tmp, config, 0)
print(res)
print(len(res))
def dfs(res=[], tmp=[], config=[], i=0):
if i == len(config):
res.append(tmp.copy())
else:
for e in config[i]:
# change spot
tmp.append(e)
# new condition,new recursion
dfs(res, tmp, config, i + 1)
# restore spot
tmp.pop(len(tmp) - 1)
# 执行主体函数
combination(a,b,c)
'''
打印结果:
[[1, 'a', '@@'], [1, 'a', '$$'], [1, 'b', '@@'], [1, 'b', '$$'],
[1, 'c', '@@'], [1, 'c', '$$'], [1, 'd', '@@'], [1, 'd', '$$'],
[2, 'a', '@@'], [2, 'a', '$$'], [2, 'b', '@@'], [2, 'b', '$$'],
[2, 'c', '@@'], [2, 'c', '$$'], [2, 'd', '@@'], [2, 'd', '$$'],
[3, 'a', '@@'], [3, 'a', '$$'], [3, 'b', '@@'], [3, 'b', '$$'],
[3, 'c', '@@'], [3, 'c', '$$'], [3, 'd', '@@'], [3, 'd', '$$']]
24
'''
方法二的改进, 1)简化了参数, 2)增加了参数类型声明
import itertools
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ['@@', '$$']
#简化了参数, 增加了参数类型声明
def combination(*args:list):
config = [e for e in args]
res = []
tmp = []
dfs(res, tmp, config, 0)
print(res)
print('combination num:', len(res))
# dfs没变动
def dfs(res=[], tmp=[], config=[], i=0):
if i == len(config):
res.append(tmp.copy())
else:
for e in config[i]:
# change spot
tmp.append(e)
# new condition,new recursion
dfs(res, tmp, config, i + 1)
# restore spot
tmp.pop(len(tmp) - 1)
# 执行主体函数
combination(a,b,c)
'''
打印结果:
[[1, 'a', '@@'], [1, 'a', '$$'], [1, 'b', '@@'], [1, 'b', '$$'],
[1, 'c', '@@'], [1, 'c', '$$'], [1, 'd', '@@'], [1, 'd', '$$'],
[2, 'a', '@@'], [2, 'a', '$$'], [2, 'b', '@@'], [2, 'b', '$$'],
[2, 'c', '@@'], [2, 'c', '$$'], [2, 'd', '@@'], [2, 'd', '$$'],
[3, 'a', '@@'], [3, 'a', '$$'], [3, 'b', '@@'], [3, 'b', '$$'],
[3, 'c', '@@'], [3, 'c', '$$'], [3, 'd', '@@'], [3, 'd', '$$']]
24
'''
总结:以上两种方法的输出结果是相同的
来源:CSDN
作者:littlehaes
链接:https://blog.csdn.net/littlehaes/article/details/103461622