英文:
Args and Tuples in Python
问题
我尝试使用下面的代码来实现,但最终收到一个TypeError错误,错误信息为unsupported operand type(s) for +=: 'int' and 'str'
def add(*args):
sum = 0
for i in args:
sum += i
return sum
print(add("1", "2", "3", "4"))
英文:
When you are trying to use *args, and I want to display a list of strings.
I attempted it via the code below but I end up receiving a TypeError stating unsupported operand type(s) for +=: 'int' and 'str'
def add(*args):
sum = 0
for i in args:
sum += i
return sum
print(add("1", "2", "3", "4"))
答案1
得分: 1
你正在传递字符串,因此在第一个循环迭代中,你试图将"1"
添加到0
。这是行不通的。
你需要将字符串转换为int
。
def add(*args):
sum = 0
for i in args:
sum += int(i)
return sum
print(add("1", "2", "3", "4"))
当然,这会引发一个可能的情况,即其中一个字符串无法转换为int
,在这种情况下,你将得到一个ValueError
异常。如果你只想忽略这些情况,可以像下面这样做。
def add(*args):
sum = 0
for i in args:
try:
sum += int(i)
except ValueError:
pass
return sum
print(add("1", "2", "3", "4"))
英文:
You are passing strings, so on your first loop iteration you're trying to add "1"
to 0
. This will not work.
You convert the string to an int
.
def add(*args):
sum = 0
for i in args:
sum += int(i)
return sum
print(add("1", "2", "3", "4"))
Of course, this raises the possibility of one of those strings not being something that can convert to an int
in this case you will get a ValueError
exception. If you wanted to just ignore those, you might do something like the following.
def add(*args):
sum = 0
for i in args:
try:
sum += int(i)
except ValueError:
pass
return sum
print(add("1", "2", "3", "4"))
答案2
得分: 0
让我们将第一个参数用作初始值,然后将其他参数添加到它。这样,add
函数可以对所有可能类型的参数进行求和:
def add(*args):
it = iter(args)
s = next(it) # 参数的第一个值
for v in it: # 所有其他值
s += v
return s
print(add(1, 2, 3, 4))
print(add('1', '2', '3', '4'))
print(add(['1', '2'], ['3', '4']))
结果输出如下:
10
1234
['1', '2', '3', '4']
英文:
Let's use first arg as an initial value and add others to it. This way add
can sum up all possible types of arguments:
def add(*args):
it = iter(args)
s = next(it) # args first value
for v in it: # all others
s += v
return s
print(add(1, 2, 3, 4))
print(add('1', '2', '3', '4'))
print(add(['1', '2'], ['3', '4']))
> $ python add.py
> 10
> 1234
> ['1', '2', '3', '4']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论