python打印多个列表的所有组合

霸气de小男生 提交于 2019-12-09 18:48:17

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
'''

总结:以上两种方法的输出结果是相同的

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!