我想問你如何在 Python 中將這個字串 '20020050055' 拆分成一個看起來像 [200, 200, 500, 5, 5] 的整數串列。
我在考慮列舉,但你有什么更好的解決方案來完成這個例子嗎?謝謝
uj5u.com熱心網友回復:
一種方法,使用正則運算式查找所有:
inp = '20020050055'
matches = re.findall(r'[1-9]0*', inp)
print(matches) # ['200', '200', '500', '5', '5']
如果由于某種原因不能使用正則運算式,這里有一個迭代方法:
inp = '20020050055'
matches = []
num = ''
for i in inp:
if i != '0':
if num != '':
matches.append(num)
num = i
else:
num = num i
matches.append(num)
print(matches) # ['200', '200', '500', '5', '5']
這里的想法是一次構建每個匹配一個數字。當我們遇到一個非零數字時,我們開始一個新的匹配。對于零,我們一直將它們連接起來,直到到達輸入的末尾或下一個非零數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521888.html
標籤:细绳列表分裂整数枚举
