簡體   English   中英

將整數字符串拆分為所有可能的數字列表

[英]Split string of integers to all possible list of numbers

我有一個整數字符串,例如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']

您需要所有組合,因此可以使用itertools.combinations和一個generator表達式來生成所有它們:

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']

您可以使用combinationsitertools庫合並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]

更新由於只需要順序組合,因此可以使用字符串中的所有子字符串(使用如何在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]

您是否正在尋找這樣的東西:

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)])

我建議看看子字符串,這也是我在上面的示例中所做的。
鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM