将数组/列表传递给 Python 函数 [英] Passing an array/list into a Python function
问题描述
我一直在研究将数组或列表(Python 倾向于调用它们)传递到函数中.
I've been looking at passing arrays, or lists, as Python tends to call them, into a function.
我阅读了一些关于使用 *args 的内容,例如:
I read something about using *args, such as:
def someFunc(*args)
for x in args
print x
但不确定这是对还是错.似乎没有什么能如我所愿.我曾经能够轻松地将数组传递给 PHP 函数,这让我很困惑.看来我也不能这样做:
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:
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.
推荐答案
当您使用以下语法定义函数时:
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.
这篇关于将数组/列表传递给 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!