[英]Permutations in list of lists
所以说我有一个清单清单
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
如何在每个列表只能选择1个项目的限制下获得所有可能的排列? 意味着147或269是可能的排列,而145将是错误的,因为4和5在同一列表中。 此外,这对于包含任意数量列表的列表如何起作用?
这对我适用于Python 2.7和3.5
import itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list(itertools.product(*l)))
它返回
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]
这在python 3中有效,请参阅python 2最后一行的注释
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
row1, row2, row3 = l
# get all the permutations as lists [1,4,7], etc.
permutations = ([x, y, z] for x in row1 for y in row2 for z in row3)
# get strings to have a more easily readable output
permutation_strings = (''.join(map(str, permutation))
for permutation in permutations)
print(*permutation_strings)
# in python2 you can use: print list(permutation_strings)
我不会称呼您正在寻找的排列,但是以下递归算法应该返回我认为您想看到的内容
def get_all_possibilities(S, P=[]):
if S == []:
return P
s = S[0]
if P == []:
for x in s:
P.append(str(x))
return get_all_possibilities(S[1:], P)
else:
new_P = []
for x in s:
for p in P:
new_P.append(p + str(x))
return get_all_possibilities(S[1:], new_P)
print get_all_possibilities([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
我的输出是以下27个项目,如果愿意,以后可以将其转换回整数;
[“ 147”,“ 247”,“ 347”,“ 157”,“ 257”,“ 357”,“ 167”,“ 267”,“ 367”,“ 148”,“ 248”,“ 348”,“ 158','258','358','168','268','368','149','249','349','159','259','359','169' ,“ 269”,“ 369”]
您可以使用递归。
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def permutate(w, l):
for x in l[0]:
if len(l) > 1:
permutate(w + str(x), l[1:])
else:
print w + str(x)
permutate("", l)
您可以为此使用itertools !
from itertools import product
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list(product(*l)))
注意事项:
我传递*l
,而不是简单的l
作为product
预计iterables作为参数,而不是一个iterables的列表; 编写此内容的另一种方式是:
product([1, 2, 3], [4, 5, 6], [7, 8, 9])
即,将每个列表作为单个参数传递。 *l
为您将l
的元素解压缩为参数。
product
不返回列表,而是生成器。 您可以将其传递给任何期望可迭代的对象。 “打印”生成器将无济于事(您不会看到结果列表的内容,但是<itertools.product object...>
只是有点有趣); 这就是为什么我使用list()
强制转换为列表的原因
print()
可使此代码与Python 2和3兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.