python - 用 str、float、int 和元组除法

标签 python python-3.x

基本上,我希望能够将 int、str、tuple 和 float 分成两半。我在区分输入类型然后返回相同类型时遇到问题。

例如,half(7) 应该返回 3(不是 3.0!),half(9.0) 应该返回 4.5,half("seventeen") 应该返回 "seve",half((1,2,3,4 ,5,6,7)) 应该返回 (1,2,3)。我试过这段代码但没有成功:

def half(x):
    """returns half of the input, rounded down

    str -> str, int -> int, float -> float, tuple -> tuple"""
    return int(x/2)
    if x is float:
        return float(x/2)
    if x is tuple:
        return tuple(x/2)
    if x is str:
        return str(x/2)

最佳答案

只需使用 functools.singledispatch , 它根据第一个参数的类型选择实现:

from functools import singledispatch

@singledispatch
def half(x):
    raise TypeError()

@half.register(int)
def _(x):
    return x // 2

@half.register(float)
def _(x):
    return x / 2

@half.register(tuple)
def _(x):
    return x[:len(x) // 2]

@half.register(str)
def _(x):
    return x[:len(x) // 2]

如果您愿意,可以将其缩短为将 lambda 传递给 half.register 而不是使用装饰器和函数语句:

from functools import singledispatch

@singledispatch
def half(x):
    raise TypeError()

half.register(int, lambda x: x // 2)
half.register(float, lambda x: x / 2)
half.register(tuple, lambda x: x[:len(x) // 2])
half.register(str, lambda x: x[:len(x) // 2])

关于python - 用 str、float、int 和元组除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466019/

相关文章:

eclipse 中 MySQL 的 python 问题

python - 在matplotlib中写一个直立的mu

python-3.x - botocore.exceptions.ClientError : An error occurred (ExpiredTokenException) The security token included in the request is expired

python-3.x - 有条件地分割长行的最 Pythonic/最有效的方法是什么?

python - Python 3 上的 CSV 写入错误

python - S3 PutObject 无提示故障?

python - 如何一次将一个超大文件读入 numpy 数组 N 行

python - 有没有一种Python式的方法来迭代两个列表的差异?

python - 用户名生成器 Python

Python,如何将图像设置到ttk.notebook选项卡