参数和元组在Python中

huangapple go评论62阅读模式
英文:

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']

huangapple
  • 本文由 发表于 2023年6月22日 05:24:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定