python列表索引中split命令超出范围的尝试

2024-06-29 00:26:54 发布

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

我是编程新手,我尝试按如下方式拆分输入字符串:

string = ['1981+198-19871*1981/555'] --> ['1981','198','19871','1981','555'] 

使用两个循环,我不明白为什么它会返回一个错误:“列表索引超出范围”

operatori = ["+","-","*","/"]
string = ['1981+198-19871*1981/555']

for operatore in operatori:
   for i in range(len(string)):
        string = string[i].split(operatore)
        print(operatore)

Tags: 字符串in列表forstringlen编程错误
2条回答

不要重新发明轮子。让标准库为您服务:

Python 3.7.5 (default, Dec 15 2019, 17:54:26) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.split('\W+', '1981+198-19871*1981/555')
['1981', '198', '19871', '1981', '555']
>>>

您甚至可以使用数字以外的任何内容作为分隔符:

>>> re.split('\D+', '1981+198-19871*1981/555abc12')
['1981', '198', '19871', '1981', '555', '12']
>>> 

最后,如果您只想在操作符+*/-上拆分,只需执行以下操作:

>>> re.split('[+*/-]', '1981+198-19871*1981/555abc12')
['1981', '198', '19871', '1981', '555abc12']
>>>

以下是两种解决任务的方法。你知道吗

第一个方法不导入任何内容,第二个方法使用带有转义运算符列表的re模块:

import re

operators = ['+', '-', '*', '/']
strings = ['1981+198-19871*1981/555']


def split_string(data: list, operators: list):
    for elm in data:
        out = ''
        for k in elm:
            if k not in operators:
                out += k
            else:
                yield out
                out = ''
        if out:
            yield out  # yield the last element


def re_split_string(data: list, operators: list):
    for elm in data:
        escaped = ''.join([re.escape(operator) for operator in operators])
        if escaped:
            pattern = r'[{operators}]'.format(operators=escaped)
            yield from re.split(pattern, elm)
        else:
            yield elm


first = list(split_string(strings, operators))
print(first)
second = list(re_split_string(strings, operators))
print(second)

输出:

['1981', '198', '19871', '1981', '555']
['1981', '198', '19871', '1981', '555']

PS:如果您想查看每个方法的性能,让我们使用一个大字符串strings = ['1981+198-19871*1981/555' * 1000]

我的计算机中的结果:

In [1]: %timeit split_string(strings, operators)                                                                    
211 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]: %timeit re_split_string(strings, operators)                                                                 
211 ns ± 0.49 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

如您所见,这两个方法的执行时间几乎相同。你知道吗

相关问题 更多 >