Python - 在一行中将函数返回值转换为 int

标签 python

我想在一行中将从函数返回的值转换为 int,但当我尝试时出现以下错误:

TypeError: int() argument must be a string or a number, not 'tuple'

我的代码如下:

def test_func():
    return 3.4, 3.5


a, b = int(test_func())

print a , b

最佳答案

改为这样做

def test_func():
    return 3.4, 3.5

a, b = map(int, test_func())

print a, b
>>> 3 3

int 是一种可以从 float (int(3.4))、字符串 (int("3")) 构造的类型和其他东西,但每次使用它时都必须创建一个整数值;你不能用两个值来调用它。相反,您必须对 test_func 返回的元组中的每个值调用 int。为此,您可以调用 map 对元组的每个值调用 int 函数。这将返回一个序列(或 Python 3 中的生成器),该序列将被迭代以将其解包为 ab 变量,从而给出所需的结果。

关于Python - 在一行中将函数返回值转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45835452/

相关文章:

python - .fits 文件的转换

python - 使用 python,如何在窗口中显示 RGB 值矩阵?

python - 使用 Python 进行精确的事件同步

python - 如何为 Windows 获取预构建的 *debug* 版本的 Python 库(例如 Python27_d.dll)

python - Subprocess.Popen() => 无输出

python - 如何关联哪个奇异值对应于哪个条目?

ascii的Python产物,错误的启动

python - 返回模型 Django Rest Framework 的键/属性 JSON 对象而不是 JSON 数组

python - 基于列值的自定义分组

python正则表达式拆分第一个字符