首页 > 解决方案 > 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)

我知道这个问题非常基本,但我需要知道它是否可能。如果没有,我将创建所有函数并为每个参数添加引号。谢谢。

标签: pythonfunction

解决方案


您只需要将字符串(字段/列名)作为参数传递给您的函数,该参数将存储到变量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')

推荐阅读