我想在一行中将从函数返回的值转换为 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 中的生成器),该序列将被迭代以将其解包为 a
和 b
变量,从而给出所需的结果。
关于Python - 在一行中将函数返回值转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45835452/