所以我在创建的代码下方有此代码。该代码将列出某个值的所有可能组合,在此示例中为“ a”,“ b”,“ c”,“ d”。如果我使用此代码,结果将是这样的:a,aa,ab,ac,ad,aaa,aab,aac,aad,aba,abb,abc等。如何简化循环代码,以便我可以输入更多的值而无需创建更多的for循环?
n = "abcd"
for c in n:
print(c)
for c1 in n:
print(c+c1)
for c2 in n:
print(c+c1+c2)
for c3 in n:
print(c+c1+c2+c3)
答案 0 :(得分:2)
https://docs.python.org/2/library/itertools.html
您需要的是Itertools的排列组合。
itertools.permutations([1, 2, 3])
答案 1 :(得分:2)
from itertools import combinations
n = "abcd"
print ([''.join(l) for i in range(len(n)) for l in combinations(n, i+1)])
输出:
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd', 'abcd']
编辑:
from itertools import combinations_with_replacement
n = "abcd"
comb = []
for i in range(1, len(n)+1):
comb += list(combinations_with_replacement(n, i))
print([''.join(c) for c in comb])
输出:
['a', 'b', 'c', 'd', 'aa', 'ab', 'ac', 'ad', 'bb', 'bc', 'bd', 'cc', 'cd', 'dd', 'aaa', 'aab', 'aac', 'aad', 'abb', 'abc', 'abd', 'acc', 'acd', 'add', 'bbb', 'bbc', 'bbd', 'bcc', 'bcd', 'bdd', 'ccc', 'ccd', 'cdd', 'ddd', 'aaaa', 'aaab', 'aaac', 'aaad', 'aabb', 'aabc', 'aabd', 'aacc', 'aacd', 'aadd', 'abbb', 'abbc', 'abbd', 'abcc', 'abcd', 'abdd', 'accc', 'accd', 'acdd', 'addd', 'bbbb', 'bbbc', 'bbbd', 'bbcc', 'bbcd', 'bbdd', 'bccc', 'bccd', 'bcdd', 'bddd', 'cccc', 'cccd', 'ccdd', 'cddd', 'dddd']
答案 2 :(得分:1)
您可以使用itertools模块来解决您的问题。您需要具有所有可能长度的combinations_with_replacement函数:
import itertools as it
n = "abcd"
result = []
for l in range(len(n)):
result += list(it.combinations_with_replacement(n, l+1))
print(result)
[('a',), ('b',), ('c',), ('d',), ('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'b'), ('b', 'c'), ('b', 'd'), ('c', 'c'), ('c', 'd'), ('d', 'd'), ('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'c'), ('a', 'c', 'd'), ('a', 'd', 'd'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'b', 'd'), ('b', 'c', 'c'), ('b', 'c', 'd'), ('b', 'd', 'd'), ('c', 'c', 'c'), ('c', 'c', 'd'), ('c', 'd', 'd'), ('d', 'd', 'd')]
答案 3 :(得分:0)
要获得340个元素的相同结果,可以使用itertools.product
:
product(n, repeat=1)
product(n, repeat=2)
...
product(n, repeat=4)
要打印结果,可以使用以下循环:
from itertools import product
n = "abcd"
for i in range(1, 5):
for prod in product(n, repeat=i):
print(''.join(prod))
要获得额外的级别,您可以在range
中轻松增加5。注意:打印顺序与代码中的稍有不同。