*args returns a list containing only those arguments that are even I tried in two ways but still I am getting the same error

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

*args returns a list containing only those arguments that are even I tried in two ways but still I am getting the same error

问题

*args返回一个只包含偶数参数的列表。

这是我尝试的代码:

def myfunc(*args):
     for n in args:
         if n%2 == 0:
             return list(args)
             
print(myfunc(1,2,3,4,5,6,7,8,9))   

错误信息:

错误详情
列表不同:[-2, 4] != [-1, -2, 4, 3, 5]

第一个不同的元素 0:
-2
-1

第二个列表包含额外的3个元素。
第一个额外的元素 2:
4

- [-2, 4]
+ [-1, -2, 4, 3, 5]:这是错误的

我想了解这个错误的原因。

英文:

*args returns a list containing only those arguments that are even

This is what I tried:

def myfunc(*args):
     for n in args:
         if n%2 == 0:
             return list(args)
             
print(myfunc(1,2,3,4,5,6,7,8,9))   

error:

Error details
Lists differ: [-2, 4] != [-1, -2, 4, 3, 5]

First differing element 0:
-2
-1

Second list contains 3 additional elements.
First extra element 2:
4

- [-2, 4]
+ [-1, -2, 4, 3, 5] : This is incorrect  

I want to understand the error

答案1

得分: 2

你的函数有几个问题。首先,当我运行你的代码时,我没有得到那个错误。我得到的是输入的列表。看起来你正在使用一个测试框架。

如果你想要得到一个包含偶数参数的列表,你可以使用列表推导来高效地实现:

args = [1,2,3,4,5,6,7,8,9,10]
output = [arg for arg in args if arg%2 == 0]
print(output)

另外,你的函数如果一个元素是偶数,就会返回整个参数列表。函数会在找到第一个偶数元素后终止。如果你想要在函数中实现这个功能,在遍历完所有元素后再返回列表。

def myfunc(*args):
    result = []
    for arg in args:
        if arg%2 == 0:
            result.append(arg)
    return result

print(myfunc(1,2,3,4,5,6,7,8,9,10))
英文:

There are a couple things wrong with your function. First, when I run your code I do not get that error. I get the list that was inputted. It also looks like you are using a testing framework.
If you want to get a list of args that are even, you can do this efficiently with list comprehension:

>>> args = [1,2,3,4,5,6,7,8,9,10]
>>> output = [arg for arg in args if arg%2 == 0]
>>> print(output)
[2, 4, 6, 8, 10]

You are also returning the entire list of args if one of the elements is even. The function will terminate after the first even element. If you want to do it in a function, return the list after you have iterated through all the elements.

>>> def myfunc(*args):
...     result = []
...     for arg in args:
...         if arg%2 == 0:
...             result.append(arg)
...     return result
...
>>> print(myfunc(1,2,3,4,5,6,7,8,9,10))
[2, 4, 6, 8, 10]

huangapple
  • 本文由 发表于 2023年8月9日 00:23:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861488.html
匿名

发表评论

匿名网友

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

确定