这段代码的问题在于它会到达某个点,在第 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)
您可以使用 python 分割字符串正则表达式模块 re
.
import re
pattern = (r'[1-9]0*')
a= '10010010010100511'
print(list(map(int, re.findall(pattern, a))))
Output
[100, 100, 100, 10, 100, 5, 1, 1]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)