小编kas*_*syc的帖子

Pythonic方式有"大小安全"切片

以下是/sf/users/62541/Explain Python的切片表示法的回答.

如果项目少于您的要求,Python对程序员很友好.例如,如果您要求[: - 2]并且只包含一个元素,则会得到一个空列表而不是错误.有时您会更喜欢错误,因此您必须意识到这可能会发生.

因此,当错误出现时,Pythonic的方法是什么?是否有更多的Pythonic方法来重写这个例子?

class ParseError(Exception):
    pass

def safe_slice(data, start, end):
    """0 <= start <= end is assumed"""
    r = data[start:end]
    if len(r) != end - start:
        raise IndexError
    return r

def lazy_parse(data):
    """extract (name, phone) from a data buffer.
    If the buffer could not be parsed, a ParseError is raised.

    """

    try:
        name_length = ord(data[0])
        extracted_name = safe_slice(data, 1, 1 + name_length)
        phone_length = ord(data[1 + name_length])
        extracted_phone = safe_slice(data, 2 + name_length, …
Run Code Online (Sandbox Code Playgroud)

python slice

7
推荐指数
2
解决办法
1055
查看次数

标签 统计

python ×1

slice ×1