将数组/列表传递给 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3961007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing an Array/List into Python
提问by Hyman Franklin
I've been looking at passing arrays, or lists, as Python tends to call them, into a function.
我一直在研究将数组或列表(Python 倾向于调用它们)传递到函数中。
I read something about using *args, such as:
我读了一些关于使用 *args 的内容,例如:
def someFunc(*args)
for x in args
print x
But not sure if this is right/wrong. Nothing seems to work as I want. I'm used to be able to pass arrays into PHP function with ease and this is confusing me. It also seems I can't do this:
但不确定这是对还是错。似乎没有什么能如我所愿。我曾经能够轻松地将数组传递给 PHP 函数,这让我很困惑。看来我也不能这样做:
def someFunc(*args, someString)
As it throws up an error.
因为它抛出了一个错误。
I think I've just got myself completely confused and looking for someone to clear it up for me.
我想我只是让自己完全糊涂了,正在找人帮我解决问题。
采纳答案by g.d.d.c
When you define your function using this syntax:
当您使用以下语法定义函数时:
def someFunc(*args):
for x in args
print x
You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:
你告诉它你期望可变数量的参数。如果您想传入一个列表(来自其他语言的数组),您可以执行以下操作:
def someFunc(myList = [], *args):
for x in myList:
print x
Then you can call it with this:
然后你可以这样调用它:
items = [1,2,3,4,5]
someFunc(items)
You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:
您需要在变量参数之前定义命名参数,在关键字参数之前定义变量参数。你也可以有这个:
def someFunc(arg1, arg2, arg3, *args, **kwargs):
for x in args
print x
Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.
其中至少需要三个参数,并支持可变数量的其他参数和关键字参数。
回答by JoshD
You can pass lists just like other types:
您可以像其他类型一样传递列表:
l = [1,2,3]
def stuff(a):
for x in a:
print a
stuff(l)
This prints the list l. Keep in mind lists are passed as references not as a deep copy.
这将打印列表 l。请记住,列表是作为引用而不是作为深层副本传递的。
回答by JAL
You don't need to use the asterisk to accept a list.
您不需要使用星号来接受列表。
Simply give the argument a name in the definition, and pass in a list like
只需在定义中给参数一个名称,然后传入一个列表,如
def takes_list(a_list):
for item in a_list:
print item
回答by Gintautas Miliauskas
Python lists (which are not just arrays because their size can be changed on the fly) are normal Python objects and can be passed in to functions as any variable. The * syntax is used for unpacking lists, which is probably not something you want to do now.
Python 列表(不仅仅是数组,因为它们的大小可以动态更改)是普通的 Python 对象,可以作为任何变量传递给函数。* 语法用于解包列表,这可能不是您现在想要做的。

