Passing an Array/List into Python

前端 未结 5 2082
耶瑟儿~
耶瑟儿~ 2020-12-12 13:31

I\'ve been looking at passing arrays, or lists, as Python tends to call them, into a function.

I read something about using *args, such as:

def some         


        
相关标签:
5条回答
  • 2020-12-12 14:12

    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.

    0 讨论(0)
  • 2020-12-12 14:32

    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.

    0 讨论(0)
  • 2020-12-12 14:32

    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.

    0 讨论(0)
  • 2020-12-12 14:32

    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
    
    0 讨论(0)
  • 2020-12-12 14:37
    def sumlist(items=[]):
        sum = 0
        for i in items:
            sum += i
    
        return sum
    
    t=sumlist([2,4,8,1])
    print(t)
    
    0 讨论(0)
提交回复
热议问题