python生成段函数

luc*_*928 0 python

用python生成分段函数的正确方法是什么?

例如:

在此处输入图片说明

wja*_*rea 5

if为此工作很好。在这里使用一个更简单的示例函数:

def f(n):
    if n in range(0, 128):  # n ? [0, 127]
        return n + 6
    elif n in range(128, 896):  # n ? [128, 895]
        return 2 * n + 1
    elif n in range(896, 1024):  # n ? [896, 1023]
        return 4 * n + 6
    else:
        raise ValueError('n must be in range(0, 1024)')
Run Code Online (Sandbox Code Playgroud)

假设您使用的是Python 3并且nint。其他任何事情都可能相对较慢。请参阅为什么Python 3中的“范围中的1000000000000000(1000000000000001)”这么快?。在其他情况下,请使用以下内容:

from numbers import Integral

def f(n):
    if not isinstance(n, Integral):  # n ? ?, as implied by the question
        raise TypeError('n must be an integer')

    if 0 <= n <= 127:  # Literally 0 ? n ? 127
        return n + 6
    ...
Run Code Online (Sandbox Code Playgroud)