首页 > 解决方案 > 列表参数在函数内部不起作用

问题描述

假设我有 4 个空变量和 2 个列表:

v1 = ""
v2 = ""
v3 = ""
v4 = ""

list_1 = ['2', '7', '18', '3']
list_2 = ['75', '8', '0', '13']

现在我想创建一个函数,它将使用列表作为参数为空变量赋值:

def assigner(list_a):
    for item in list_a:
      v1 = list_a[0]
      v2 = list_a[1]
      v3 = list_a[2]
      v4 = list_a[3]

因此,我调用该函数,然后尝试使用一个变量来检查是否已根据列表分配了新值。但我看到的只是''。这里有什么问题?

   assigner(list_1)
   print(v2)
   >>> ''

标签: python-2.7listfunctionparameters

解决方案


v1, ..., v4在内部定义assigner的是该函数的本地函数,不会影响在其外部定义的函数。任何半体面的 IDE 都会显示警告,即这些局部变量会影响同名的全局变量。

不相关,但该循环没有用处。

在这里使用一个函数是多余的,你可以解压列表:

v1, v2, v3, v4 = ['2', '7', '18', '3']

If you insist on using a function (or if you have a need for a function, ie have some logic instead of simply assigning), make sure to return the variables from the function:

# no need to define v1, ..., v4 outside

def assigner(list_a):
    v1 = list_a[0]
    v2 = list_a[1]
    v3 = list_a[2]
    v4 = list_a[3]   
    # some magic logic
    return v1, v2, v3, v4

v1, v2, v3, v4 = assigner(list_1)

Some people will suggest to actually use global variables, but 9/10 times that would be a bad suggestion.


推荐阅读