python列表组合

python列表组合

描述

主要记录下两个及多个列表的组合,我们想把两个列表进行组合生成所有可能性。例如:

a = [‘1’,’2’,’3’]

b = [‘a’,’b’,’c’]

期望得到的结果:[‘1’,’a’],[‘1’,’b’],[‘1’,’c’],[‘2’,’a’],[‘2’,’b’]··········

思考

笨办法的话就是for循环,但是写起来不美观。下面学习到几种写法,记录下。

1
2
3
4
a = ["foo","melon"]
b = [True, False]
c = list(itertools.product(a, b))
print(c) --> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]
1
2
3
4
a = ["foo","bar"]
b = [1, 2, 3]
c = [(x,y) for x in a for y in b]
print(c) --> [('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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)

Respect

https://www.codenong.com/12935194/
https://blog.csdn.net/littlehaes/article/details/103461622