为什么我总是得到一个“列表索引必须是整数或片,而不是str”?

2024-10-01 17:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个函数时,我一直得到一个“列表索引必须是整数或片,而不是str”,我不知道为什么。此函数获取一个方程式,并按数字和运算符将其拆分 ie:1+8-9=['1'、'+'、'8'、'-'、'9']

def trimFunction(p):
    list = re.split("([+ -])", p)
    if list[0] == '':
        list.remove('')
        
    counter = 0
    for x in list:
#the error happens here vvvv
        if list[x].isnumeric(): 
            counter += 1
    return list, counter 

Tags: 函数re列表ifdefcounter运算符数字
2条回答

您需要将x.isnumeric()替换为列表[x].isnumeric()

import re
def trimFunction(p):
    list = re.split("([+ -])", p)
    print(list)
    if list[0] == '':
        list.remove('')
    counter = 0
    for x in list:
#Correction
        if x.isnumeric(): 
            counter += 1
    return list, counter 
trimFunction('1+8-9')

输出 (['1'、'+'、'8'、'-'、'9'],3)

因为您正在迭代列表中作为字符串的每个项

在循环中x与给定的['1','+','8','-','9']for x in list是'1','+','8','-','9',而不是它们的索引(0,1,2,3,4)

因此,您的循环应该是:

for x in list:
    if x.isnumeric():
        counter += 1
return list, counter

for index in range(len(list)):
    if list[index].isnumeric():
        counter += 1
return list, counter

相关问题 更多 >

    热门问题