我有一串整数,例如s = "1234"
我想将它拆分为整数split = [ 1234, 1, 2, 3, 4, 12, 123, 23, 234, 34 ]
的各个顺序组合。如何在Python中对此进行编码?
我尝试了什么:
for i in range(0,len(number)-1):
x =["" + number[j] for j in range(i, len(number))]
print(x)
输出:
['1', '2', '3', '4', '5']
['2', '3', '4', '5']
['3', '4', '5']
['4', '5']
答案 0 :(得分:2)
您需要所有组合,因此您可以使用itertools.combinations
和生成器表达式来生成所有组合:
In [25]: from itertools import combinations
In [26]: list(''.join(sub) for i in range(1, len(s) + 1) for sub in combinations(s, i))
Out[26]:
['1',
'2',
'3',
'4',
'12',
'13',
'14',
'23',
'24',
'34',
'123',
'124',
'134',
'234',
'1234']
答案 1 :(得分:1)
您可以使用combinations
库中的itertools
与list comprehension
结合使用:
>>> from itertools import combinations
>>> s = "1234"
>>> [int(''.join(x)) for i in range(len(s)) for x in combinations(s, i + 1)]
[1, 2, 3, 4, 12, 13, 14, 23, 24, 34, 123, 124, 134, 234, 1234]
<强>更新强> 由于您只需要顺序组合,您可以使用字符串中的所有子字符串(使用How To Get All The Contiguous Substrings Of A String In Python?):
>>> l = len(s)
>>> [int(s[i:j+1]) for i in range(l) for j in range(i,l)]
[1, 12, 123, 1234, 2, 23, 234, 3, 34, 4]
答案 2 :(得分:0)
你在寻找像这样的东西:
stringA = "1234";
lenA = len(stringA);
# Loop through the number of times stringA is long.
for n in range(lenA):
print("---");
# Loop through string, print part of the string.
for x in range(lenA-n):
print(stringA[n:n + (x+1)])
我建议看一下子串,这也是我在上面的例子中也做的。
Link