简体   繁体   English

Python函数返回列表

[英]Python Function To Return List

Python newbie here.I wrote this function to only return even numbers as a list but I am failing at doing this. 我在这里写了Python新手函数,只将偶数作为列表返回,但我做不到。 Can you please help? 你能帮忙吗? This is my initial function which works fine but results are not coming out as a list: 这是我的初始函数,可以正常工作,但结果未列出:

def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            print (num)

When you call the function for example with the following arguments: 例如,使用以下参数调用函数时:

myfunc(1,2,3,4,5,6,7,8,9,10)

I am getting: 我正进入(状态:

2
4
6
8
10

but I need those to be in a list, what am I missing? 但我需要将它们列入列表中,我想念的是什么? This doesn't work either: 这也不起作用:

list = []
def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            print (list[num])

Much appreciated! 非常感激!

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

Your function is not returning anything. 您的函数未返回任何内容。 You may want to get the elements by 您可能希望通过以下方式获取元素

def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            yield num

Or create a temporary list: 或创建一个临时列表:

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

You can check your returned value in REPL: 您可以在REPL中检查返回的值:

>> type(print(num)) # print() returns None
NoneType

Explanation: In short, yield returns an element per time the function is iterated - and only returns an element once. 说明:简而言之, yield每次迭代该函数时都会返回一个元素-并且仅返回一次元素。 So the function is also called a "generator". 因此该函数也称为“生成器”。 There is an excellent post about yield . 关于yield一个很好的帖子 I cannot explain better than it. 我无法解释得更好。


Update: Don't use list as variable name, list is a builtin method. 更新:不要使用list作为变量名, list是一种内置方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM