python - Python:列引号之间的函数参数
问题描述
基本上我需要以下内容:
data['sales']*10
data['height']*10
我面临的根本问题是如何创建一个函数,我可以在其中编写变量名而不在函数内添加引号。这可能吗?例如,就像在“”内写一个特殊字符,表示一个词是一个参数。
def function(var1):
p=data['var1']*10 #The error is here; I tried p=data["'"+var1+"'"]*10
#Is there a way to indicate var1 is not a string,
#like p=data['&var1']*10
return p
function(sales)
function(height)
我知道这个问题非常基本,但我需要知道它是否可能。如果没有,我将创建所有函数并为每个参数添加引号。谢谢。
解决方案
您只需要将字符串(字段/列名)作为参数传递给您的函数,该参数将存储到变量var1
中。然后,您无需在var1
函数内加上引号。例如,执行以下操作
def function(var1):
p=data[var1]*10 #The error is here; I tried p=data["'"+var1+"'"]*10
#Is there a way to indicate var1 is not a string,
#like p=data['&var1']*10
return p
function('sales')
function('height')
推荐阅读
- json - 在 Angular 8 的构建期间合并两个配置文件
- c# - 计算不为空并输入到表中的行数
- javascript - 如何将文件夹路径绑定到 vuetify v-text-box?
- powershell - 如何将“y”传递给使用 PowerShell Start-Process 启动的 pscp 进程?
- java - 如何将下面的字符串转换为地图列表?
- directx - MediaFoundation SinkWriter:启用 MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS 会导致 WriteSample 失败并出现 E_FAIL 错误
- node.js - 如何在节点 js 中安排作业?
- unity3d - UNITY_ARCore : localEulerAngles 总是给出 0 值
- c - 将字符串转换为 32 位 int(有符号或无符号)并检查范围错误
- python - Python,Pandas:根据列值合并某些行的总和