這段代碼的問題是它會在第 9 行到達一個點(如果 a[c 1] != 0:),它會呼叫一個不存在的索引 3,它會給我錯誤“串列索引超出范圍”。
a= '555101'
a= list(map(int,a))
c= 0
seq= []
for i in a:
if a[c] == 1:
if a[c 1] != 0:
seq.append(i)
c = 1
elif a[c 3] == 0: #error
if a[c 2] == 0:
seq.append(1000)
c = 1
elif a[c 2] != 0:
seq.append(10)
c = 1
elif a[c 2] == 0:
if a[c 1] == 0:
seq.append(100)
c = 1
elif a[c 1] != 0:
seq.append(1)
c = 1
elif a[c] == 0:
c = 1
elif a[c] == 5:
seq.append(i)
c = 1
print(seq)
uj5u.com熱心網友回復:
這是我在沒有額外庫的情況下如何做到的。檢查不等于 0 的值以啟動一個組,只要它們出現,就使用 while 回圈將 0 添加到該組。在該程序中,您需要檢查索引是否小于輸入串列的長度。我添加了更多字串來檢查意外行為,但據我所知,它有效。
tests = [
'10010010010100511',
'00010010010100511',
'10010010010100510',
'10010051110010100',
]
def func(string):
a = list(map(int,string))
all_groups = []
group = []
i = 0
while i < len(a):
if a[i] != 0:
group.append(a[i])
j = i 1
while (j < len(a)) and (a[j] == 0):
group.append(a[j])
j = 1
all_groups.append(group)
group = []
i = j
if group:
all_groups.append(group)
i = 1
else:
i = 1
out = [int(''.join([str(digit) for digit in elem])) for elem in all_groups]
print(out, '\n')
for string in tests:
print(string)
func(string)
輸出:
10010010010100511
[100, 100, 100, 10, 100, 5, 1, 1]
00010010010100511
[100, 100, 10, 100, 5, 1, 1]
10010010010100510
[100, 100, 100, 10, 100, 5, 10]
10010051110010100
[100, 100, 5, 1, 1, 100, 10, 100]
uj5u.com熱心網友回復:
您可以使用 python regex 模塊 拆分字串re。
import re
pattern = (r'[1-9]0*')
a= '10010010010100511'
print(list(map(int, re.findall(pattern, a))))
輸出
[100, 100, 100, 10, 100, 5, 1, 1]
uj5u.com熱心網友回復:
U 可能想要包含一個檢查函式來檢查 a[c 2] > 字串 a 的長度,這樣就不會像當前那樣發生錯誤
或者更簡單的方法是使用 try 和 except ,您可以使用 except 來處理錯誤,如果索引超出范圍意味著您位于字串中的最后幾個數字
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522487.html
標籤:Python列表索引范围
