Python - 将函数返回值转换为单行中的int

时间:2017-08-23 09:13:45

标签: 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

2 个答案:

答案 0 :(得分:3)

改为

def test_func():
    return 3.4, 3.5

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

print a, b
>>> 3 3

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

答案 1 :(得分:0)

def test_func():
    return 3.4, 3.5

a, b = [int(i) for i in test_func()]

print (a, b)