Return more than one value in python function

社会主义新天地 提交于 2021-02-05 12:31:07

问题


I was trying to use *args with a for loop in python, however I don't see how to return all the values passed to the function, which should return all the even numbers

def f_even(*args):
    for item in args:
        if item%2 == 0:
            return item

The above code returns only the first value, as I guess after the return it goes out of the function. Indeed, if I use print instead, it works

I'm trying to find a way to return a tuple with all the even numbers when I pass let's say (1,2,3,4,5) to the function

Thank you!


回答1:


In python you can use list comprehension to do this. will make you code more readable and will shrink it too.

def f_even(*args):
   return [elem for elem in args if elem % 2 == 0]



回答2:


You could slightly modify you function and make it a generator by using yield. This way your function wont end after returning first even number but will keep yielding them one by one.

def f_even(*args):
    for item in args:
          if item%2 == 0:
             yield item

for i in f_even(1,2,3,4,5):
    print(i)

Output:

2
4

Or if you want to store all yielded values:

even_numbers = list(f_even(1,2,3,4,5))
print(even_numbers) # -> [2, 4]



回答3:


Done, thank you all!!

def f_even(*args): mylist = [] for item in args: if item%2 == 0: mylist.append(item) return mylist



来源:https://stackoverflow.com/questions/53685897/return-more-than-one-value-in-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!