python - 尝试拆分数字但列表索引超出范围

标签 python list indexing range

这段代码的问题在于,它会在第 9 行到达某个点(if 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 regex module 分割字符串重新

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]

关于python - 尝试拆分数字但列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74232299/

相关文章:

python - tkinter 中有点击事件处理程序吗?

python - Python 中的 float

python - cx_Oracle.DatabaseError : DPI-1039: statement was already closed

python - 如何在 python 中将值列表转换为字典?

c - 另一个计数器给一个计数器赋值,防止计数器递增?

json - JSON 数组字段的索引

python - 在 Linux Python/pip 上构建 cyrus-sasl 后无法看到 sasl.h 文件

python - 列表中元组值之间的关系根据它们的位置

python - 计算字符列表在字符串中出现的次数 - Python(没有计数或计数器)

Python 3 列表切片引发索引错误