如何解决在 Python 中使用 *args 时出现类型错误
我在多参数函数中使用元组时遇到 TypeError。这是我的代码:
def add(*args):
result = 0
for x in args:
result = result + x
return result
items = 5,7,4,12
total = add(items)
print(total)
这是错误:
Traceback (most recent call last):
File "e:\functions.py",line 9,in <module>
total = add(items)
File "e:\functions.py",line 4,in add
result = result + x
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
如果我直接输入参数而不是使用变量,我不会收到任何错误:
total = add(5,12)
我用 Java 编写代码,刚开始使用 Python,但我不明白为什么会这样。
解决方法
您将元组 items
作为单个参数传递给 add
,它被编写为期望任意数量的单个数字参数而不是单个可迭代参数(这就是 {{1 }} 语法确实如此——它采用任意数量的参数并将它们转换为函数内部的可迭代对象)。
发生 *args
是因为您的 TypeError
将 for x in args
的值作为 items
的第一个值(因为它是第一个参数),因此您的函数正在尝试执行 x
操作,该操作无效,因为您无法将 0 + (5,7,4,12)
添加到 int
(这就是错误消息所述的原因)。
要将单个项目作为单个参数传递,请执行以下操作:
tuple
或通过在调用者中镜像 total = add(5,12)
语法来解包元组,如下所示:
*
请注意,Python 有一个名为 total = add(*items)
的内置函数,它将完全按照您的意愿处理元组:
sum
通过从函数定义中的 total = sum(items)
中删除 add
,您可以从 *
函数获得相同的行为。
当你这样做时。
items = 5,12 #tuple & it looks like this (5,12)
total = add(items)
您将 items
变量传递给您的 add
函数,通常看起来像这样。
total = add((5,12))#Not like this add(5,12)
嗯……这是正确的,没有任何问题,但根据您的目标,这不是正确的方法。在此处了解有关 *args 的更多信息。
这就是您期望执行的操作,您可以按照其他答案的建议通过 unpacking
执行此操作。
add(5,12)
因为您所做的是传递了整个元组,因此您的 args
参数看起来像这样 ((5,12))
& 当您执行 for 循环时,您是 iterating
元组(这是args) 对象的值,即此 (5,12)
,然后将其添加到 int
中,这显然是所述错误。
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
,
def add(*args):
result = 0
for x in args:
result = result + x
return result
items = 5,12
total = add(*items)
print(total)
只需在 total = add(*items)
中添加一个随机 *
结果:
28
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。