简体   繁体   English

从Python中的函数返回列表

[英]Return a list from a function in Python

I'm new to python so pardon me if this is a silly question but I'm trying to return a list from a function. 我是python的新手,如果这是一个愚蠢的问题,请原谅我,但我正在尝试从函数中返回列表。 This is what I have so far but I'm getting nowhere. 到目前为止,这就是我所没有的。 Can someone tell me what I'm doing wrong here? 有人可以告诉我我在做什么错吗?

I'm trying to make a simple function that called make_a_list(1, 5, "Christian") that returns a list that looks like this: [1, 5, "Christian] 我正在尝试制作一个简单的函数,称为make_a_list(1, 5, "Christian") ,该函数返回一个如下所示的列表: [1, 5, "Christian]

def make_a_list():
    my_list = ["1", "5", "Christian"]
    for item in my_list:
    return my_list

my_list = make_a_list()

print(my_list)

You can do that like this: 您可以这样做:

def make_a_list(*args):
    return list(args)

print(make_a_list(1, 5, "Christian"))  # [1, 5, "Christian"]

But you do not have to since there is a Python built-in that already does that: 但是您不必这样做,因为已经有一个内置的Python:

print(list((1, 5, "Christian")))  # [1, 5, "Christian"]

Notice that with the second option you are passing the whole tuple and not the elements separately. 注意,使用第二个选项,您将传递整个tuple而不是分别传递元素。

I'm not sure if this is what you want, the question is unclear 我不确定这是否是您想要的,问题尚不清楚

def make_a_list(*args):
    def inner():
        return list(args)
    return inner

you would then use it like this 然后,您将像这样使用它

make_list_1 = make_a_list(1, 5, "Christian") # make_list_1 is a function
make_list_2 = make_a_list(2, 10 "A different list") # make_list_2 is a different function

list_1 = make_list_1() # list_1 is a list
print(list_1) # that we can print

In Python you do not need to make a dedicated function to create a list. 在Python中,您无需进行专门的功能即可创建列表。 You can create lists very easily. 您可以非常轻松地创建列表。 For example: 例如:

list1 = ['one', 'two', 'three']
print(list1)

>>['one','two', 'three']

Check out the following website for more information not only about lists, but other python concepts. 请访问以下网站,以获得不仅有关列表的更多信息,而且还了解其他python概念。 https://www.tutorialspoint.com/python/python_lists.htm https://www.tutorialspoint.com/python/python_lists.htm

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

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