use*_*254 4 python python-itertools python-3.x
我写了一个简单的Python程序:
#!/usr/bin/env python3.5
import sys, itertools
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.combinations_with_replacement(sCharacters, iCombinationLength):
print(''.join(aCombination))
Run Code Online (Sandbox Code Playgroud)
输出如下:
1
2
3
11
12
13
22
23
33
111
112
113
122
123
133
222
223
233
333
Run Code Online (Sandbox Code Playgroud)
然而,如果它是数字 1、2 和 3 的所有组合,则需要包括:
311
312
313
321
322
323
331
332
333
Run Code Online (Sandbox Code Playgroud)
正如您在上面看到的,事实并非如此。我看过其他帖子给出的 Combinations_with_replacement 函数作为解决方案来获取传入的字符的所有可能组合。但这似乎并没有发生。我在这里做错了什么,如何获得字符变量中字符的所有可能组合?
谢谢你的时间 ;-)
“组合”是一个不区分顺序的术语;如果你有113,那么你不需要131或311,因为它们都是相同的“组合”(如果输入序列 是combinations_with_replacement唯一的,您可以在转换为 后将输出视为所有唯一值collections.Counter;无论顺序如何,两个1s 和 a3只是collections.Counter({1: 2, 3:1}))。
如果您想要顺序敏感的版本combinations_with_replacement(所以113、131和311都是单独的输出),请itertools.product与repeat参数一起使用(repeat由于 的设计,必须通过关键字传递product,其中它采用可变长度位置参数):
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.product(sCharacters, repeat=iCombinationLength):
print(''.join(aCombination))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2363 次 |
| 最近记录: |