首页 > 解决方案 > 如何通过重复在python中获得所有组合

问题描述

代码示例

from itertools import *
from collections import Counter
from tqdm import *
#for i in tqdm(Iterable):
for i in combinations_with_replacement(['1','2','3','4','5','6','7','8'], 8):
    b = (''.join(i))
    if b == '72637721':
        print (b)

当我尝试产品时

    for i in product(['1','2','3','4','5','7','6','8'], 8):
TypeError: 'int' object is not iterable

我怎样才能得到所有的组合?(我在没有测试之前就相信了,所以现在我做错了)

我读到了关于combinations_with_replacement return all ,但我怎么看它是谎言

我使用python 3.8

提出要求

11111111 11111112 11111113 11111114 11111115 11111116 11111117 11111118 11111122 11111123 11111124 11111125 11111126 11111127 11111128 11111133 11111134 11111135 11111136 11111137 11111138 11111144 11111145 11111146 11111147 11111148 11111155 11111156 11111157 11111158 11111166 11111167 11111168 11111177 11111178 11111188 11111222 11111223 11111224 11111225 11111226 11111227 11111228 11111233 11111234 11111235 11111236 11111237 11111238 11111244 11111245 11111246 11111247 11111248 11111255 11111256 11111257 11111258 11111266 11111267 11111268 11111277 11111278 1111128

它开始在结束时给出什么

56666888 56668888 56688888 56888888 58888888 77777777 77777776 77777778 77777766 77777768 77777788 77777666 77777668 77777688 77777888 77776666 77776668 77776688 77776888 77778888 77766666 77766668 77766688 77766888 77768888 77788888 77666666 77666668 77666688 77666888 77668888 77688888 77888888 76666666 76666668 76666688 76666888 76668888 76688888 76888888 78888888 66666666 66666668 66666688 66666888 66668888 66688888 66888888 68888888 88888888

更清楚地认为它是如何从 1111 1111 计数到 8888 8888 的(但是对于字符,所以这就是为什么我使用尝试在排列/结合重复时进行操作......它错过了该符号的一些可能组合。

举个例子,我尝试做的是,对所有可能的十六进制数变体进行排列,比如从 0 到 F,但不仅要对它们进行排列,还要对任何字符进行排列。

这仅在示例 ['1','2','3','4','5','6','7','8'] 这可以是 ['a','b',' x','c','d','g','r','8'] 等。

标签: python-3.xcombinationspermutationitertools

解决方案


这是将打印所有组合的更新代码。您的列表是否包含字符串和数字并不重要。

为确保您只对特定数量的元素进行组合,我建议您这样做:

comb_list = [1, 2, 3, 'a']
comb_len = len(comb_list)

并将该行替换为:

comb = combinations_with_replacement(comb_list, comb_len)


from itertools import combinations_with_replacement
comb = combinations_with_replacement([1, 2, 3, 'a'], 4)
for i in list(comb): 
    print (''.join([str(j) for j in i])) 

结果如下:

1111
1112
1113
111a
1122
1123
112a
1133
113a
11aa
1222
1223
122a
1233
123a
12aa
1333
133a
13aa
1aaa
2222
2223
222a
2233
223a
22aa
2333
233a
23aa
2aaa
3333
333a
33aa
3aaa
aaaa

我不知道你想做什么。这是尝试开始对话以获得最终答案的尝试:

samples = [1,2,3,4,5,'a','b']
len_samples = len(samples)
for elem in samples:
    print (str(elem)*len_samples)

其输出如下:

1111111
2222222
3333333
4444444
5555555
aaaaaaa
bbbbbbb

这是你想要的吗?如果不是,请解释您的问题部分您期望的输出。


推荐阅读