在python函数中返回多个值 [英] Return more than one value in python function

查看:59
本文介绍了在python函数中返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 python 中将 *args 与 for 循环一起使用,但是我没有看到如何返回传递给函数的所有值,该函数应该返回所有偶数

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

当我将 (1,2,3,4,5) 传递给函数时,我试图找到一种方法来返回一个包含所有偶数的元组

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

谢谢!

推荐答案

在 python 中,你可以使用列表理解来做到这一点.将使您的代码更具可读性,并且也会缩小它.

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]

这篇关于在python函数中返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆