实现一个与 str.split 方法相同的函数(当然不使用 str.split 本身)

问题描述 投票:0回答:1

我尝试了适用于某些拆分的代码。但它在大多数断言上始终失败。你能帮忙吗?

输入导入列表

def split(data: str, sep=None, maxsplit=-1):
    empty_str = ""
    my_list = []
    for c in data:
        if c[0] == ',':
            my_list.append(c)
        elif c == ' ' and empty_str != '':
            my_list.append(empty_str)
            empty_str = ''
        else:
            empty_str += c
    if maxsplit == 0:
        return data
    if empty_str:
        my_list.append(empty_str)
    return my_list

if __name__ == '__main__':
    assert split('') == []
    assert split(',123,', sep=',') == ['', '123', '']
    assert split('test') == ['test']
    assert split('Python    2     3', maxsplit=1) == ['Python', '2     3']
    assert split('    test     6    7', maxsplit=1) == ['test', '6    7']
    assert split('    Hi     8    9', maxsplit=0) == ['Hi     8    9']
    assert split('    set   3     4') == ['set', '3', '4']
    assert split('set;:23', sep=';:', maxsplit=0) == ['set;:23']
    assert split('set;:;:23', sep=';:', maxsplit=2) == ['set', '', '23']
python split
1个回答
0
投票

您的代码中存在一些问题,首先,正如注释中所述,您没有使用

sep
参数,然后 maxsplit 也仅与 0 一起使用,因此您可能会遗漏其他内容。

最重要的是,你的断言非常个人化,为什么不与现有的

split
方法进行比较?

这是一个代码片段示例,应该可以让您更接近您的目标:

import math

def split(data: str, sep=',', maxsplit=math.inf):
    tosplit = ""
    splits = 0
    my_list = []
    for c in data:
        if c == sep and splits < maxsplit:
            my_list.append(tosplit)
            splits += 1
            tosplit = ""
        else:
            tosplit += c
    my_list.append(tosplit)
    return my_list

但是你必须再次查看你的断言,因为它们可能也不适用于

str.split
方法。

© www.soinside.com 2019 - 2024. All rights reserved.