Python- 函数不接受数字作为 2 个数字,尽管它有一个逗号
Python- Function not accepting number as 2 numbers, despite it having a comma
这可能是相当明显的,但由于某些原因它就是行不通。
我的功能是这样的:
def hours(num,num2):
return num , " hours and " , num2 , " minutes."
插入的函数是:
total(final) #this isn't really important, just wanted to show that it was a function
#plugging into another function. This function puts out 2 numbers in a (n,m)
#format.
结果是一个 (n,m) 格式的数字
但是,当我尝试将 (n,m) 插入第一个函数时,它不起作用?我认为应该是因为它用逗号分隔,这就是第一个函数所要求的,但我不知道。
尝试使用 *
调用 hours() 来解压元组:
time = (3, 15)
print(hours(*time)) # unpack the tuple
这是文档的相关部分:
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
根据你问题的措辞有点难以判断,但我认为你的意思是:
hours(total(final))
没有按预期工作,其中 total
returns 类似于 return n,m
?
如果是这样,您需要使用通常所说的 splat 运算符,python 的解包参数语法:
hours(*total(final))
*
运算符在方法的输入参数上使用时,会展开 list/tuple/iteratable 并将结果用作方法的位置参数。即
ex = 1,2
foo(*ex)
# is equivalent to
foo(1,2)
如果省略 *
运算符,元组将作为单个位置参数一起传递,而不是解包。
试试这个:
def total(final):
return (10, 20)
def hours(num1, num2):
print num1, num2
result = total(4)
hours(*result) #explode result tuple into two arguments
--output:--
10 20
一个元组,如 (10, 20)
是一个单一的 事物 ,因此它只算作一个参数。它不是这样工作的:
hours( (10, 20) )
| |
V V
def hours(num1, num2):
相反,它是这样工作的:
hours( (10, 20) )
|------|
|
V
def hours(num1, num2):
...这意味着您没有为 num2 提供参数。
然而,写作:
hours( *(10, 20) )
将元组分解为两个参数:
hours(10, 20)
这可能是相当明显的,但由于某些原因它就是行不通。
我的功能是这样的:
def hours(num,num2):
return num , " hours and " , num2 , " minutes."
插入的函数是:
total(final) #this isn't really important, just wanted to show that it was a function
#plugging into another function. This function puts out 2 numbers in a (n,m)
#format.
结果是一个 (n,m) 格式的数字 但是,当我尝试将 (n,m) 插入第一个函数时,它不起作用?我认为应该是因为它用逗号分隔,这就是第一个函数所要求的,但我不知道。
尝试使用 *
调用 hours() 来解压元组:
time = (3, 15)
print(hours(*time)) # unpack the tuple
这是文档的相关部分: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
根据你问题的措辞有点难以判断,但我认为你的意思是:
hours(total(final))
没有按预期工作,其中 total
returns 类似于 return n,m
?
如果是这样,您需要使用通常所说的 splat 运算符,python 的解包参数语法:
hours(*total(final))
*
运算符在方法的输入参数上使用时,会展开 list/tuple/iteratable 并将结果用作方法的位置参数。即
ex = 1,2
foo(*ex)
# is equivalent to
foo(1,2)
如果省略 *
运算符,元组将作为单个位置参数一起传递,而不是解包。
试试这个:
def total(final):
return (10, 20)
def hours(num1, num2):
print num1, num2
result = total(4)
hours(*result) #explode result tuple into two arguments
--output:--
10 20
一个元组,如 (10, 20)
是一个单一的 事物 ,因此它只算作一个参数。它不是这样工作的:
hours( (10, 20) )
| |
V V
def hours(num1, num2):
相反,它是这样工作的:
hours( (10, 20) )
|------|
|
V
def hours(num1, num2):
...这意味着您没有为 num2 提供参数。
然而,写作:
hours( *(10, 20) )
将元组分解为两个参数:
hours(10, 20)