【发布时间】:2021-07-24 08:44:08
【问题描述】:
我有一个列表L = [3, 4, 1, 5, 9],我想通过使用列表L 中的数字来获取所有可能的数字。我的意思是,我想得到这样的输出:[3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.]
我正在使用此代码:
from itertools import combinations
possible_numbers = []
output = (sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], []))
output.pop(0)
for x in output:
strings = [str(integer) for integer in x]
a_string = "".join(strings)
possible_numbers.append(int(a_string))
print(output)
但我得到了这种类型的输出:
[3,4,1,5,9,34,31,35,39, 4145,49,15,19,59,341,345,349,315,319,359,415,419,459,159,3415,3419,3459,3159,4159,34159]
显然这不是我想要的,因为列表L 可以形成更多可能的组合。谁能帮忙。
【问题讨论】:
-
也许你应该用正常的
for循环将output = (sum ....)行重写为几行。这对我来说太复杂了,我无法理解它是否正确(显然,对你来说也是如此)。 -
使用
permutations而不是combinations(然后我在列表中得到 325 个数字) -
@mkrieger1 不,在发布这个问题之前,我访问了那个答案,但它对我不起作用,因为我想要一个数字列表,而不是整数组合。