在python中将数组作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36620025/
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
Pass array as argument in python
提问by user12345
I am new to python. Now I need to declare the array of size 20 and pass the array to a function.
我是python的新手。现在我需要声明大小为 20 的数组并将该数组传递给一个函数。
The function expecting the array is as:
期望数组的函数是:
function(*args)
The args
is an input to the function()
.
的args
是一个输入到function()
。
Can anyone help me, how to pass array in python?
谁能帮我,如何在python中传递数组?
回答by PM 2Ring
When you say "array" I assume you mean a Python list
, since that's often used in Python when an array would be used in other languages. Python actually has several array types: list
, tuple
, and array
; the popular 3rd-party module Numpyalso supplies an array type.
当您说“数组”时,我假设您的意思是 Python list
,因为当数组在其他语言中使用时,它经常在 Python 中使用。Python 实际上有几种数组类型:list
, tuple
, 和array
; 流行的第 3 方模块Numpy也提供了一个数组类型。
To pass a single list (or other array-like container) to a function that's defined with a single *args
parameter you need to use the *
operator to unpack the list in the function call.
要将单个列表(或其他类似数组的容器)传递*args
给使用单个参数定义的函数,您需要使用*
运算符在函数调用中解压缩列表。
Here's an example that runs on Python 2 or Python 3. I've made a list of length 5 to keep the output short.
这是一个在 Python 2 或 Python 3 上运行的示例。我制作了一个长度为 5 的列表以保持输出简短。
def function(*args):
print(args)
for u in args:
print(u)
#Create a list of 5 elements
a = list(range(5))
print(a)
function(*a)
output
输出
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
0
1
2
3
4
Note that when function
prints args
the output is shown in parentheses ()
, not brackets []
. That's because the brackets denote a list, the parentheses denote a tuple. The *a
in the call to function
unpacks the a
list into separate arguments, but the *arg
in the function
definition re-packs them into a tuple.
请注意,function
打印时args
输出显示在括号中()
,而不是括号中[]
。那是因为括号表示一个列表,括号表示一个元组。该*a
呼叫到function
拆包a
列表为单独的参数,但*arg
在function
定义重新包装它们放入一个元组。
For more info on these uses of *
please see Arbitrary Argument Listsand Unpacking Argument Listsin the Python tutorial. Also see What does ** (double star) and * (star) do for Python parameters?.
有关这些用途的详细信息*
,请参阅任意参数列表和开箱参数列表在Python教程。另请参阅**(双星)和 *(星)对 Python 参数有何作用?.
回答by xio
回答by Marc Cabos
I think that what you need is easier than expected:
我认为您需要的比预期的要容易:
def arrayIn(arrayFunc):
print(arrayFunc)
arraySize = 20
mineArray = [None]*arraySize
arrayIn(mineArray)