python-2.7 - 列表参数在函数内部不起作用
问题描述
假设我有 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)
>>> ''
解决方案
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.
推荐阅读
- python - 将字典的子集保存为新变量并保留原始字典
- node.js - 如何从 NodeJS 中的异步调用返回对象?从回调中返回对象 [object Object]
- nginx - HLS 流、nginx 反向代理、带变量的 proxy_pass
- arduino - 串行流上的arduino json
- .net - XPO中如何使用基类的字段做联合唯一索引
- mule - 如何在运行时根据请求在不同的属性文件之间切换?
- java - 在 Linux 虚拟机上托管 Java 服务器
- apache-kafka - Kafka connect confluent jdbc不控制MSSQL数据库中的会话池
- javascript - 如何在使用 navigator.mediaDevices.getUserMedia 录制音频时修复大量回声?
- android - zzrb.zza 导致每个其他 cameraX analyzer.analyze 帧除以零算术异常