[英]python equivalent of get() in R (= use string to retrieve value of symbol)
In R, the get(s)
function retrieves the value of the symbol whose name is stored in the character variable (vector) s
, eg 在R中,
get(s)
函数检索其名称存储在字符变量(vector) s
中的符号的值,例如
X <- 10
r <- "XVI"
s <- substr(r,1,1) ## "X"
get(s) ## 10
takes the first symbol of the Roman numeral r
and translates it to its integer equivalent. 接受罗马数字
r
的第一个符号,并将其转换为其等效的整数。
Despite spending a while poking through R-Python dictionaries and Googling various combinations of "metaprogramming", "programming on the language", "symbol", "string", etc., I haven't come up with anything. 尽管花了一些时间在R-Python词典上进行拨码,并搜索了“元编程”,“语言编程”,“符号”,“字符串”等各种组合,但我什么都没想。 (I am a very experienced R user and a novice Python user.)
(我是一个非常有经验的R用户和Python新手。)
(I know the example above is a (very!) poor way to approach the problem. I'm interested in the general answer to this question, not specifically in converting Roman numerals to integers ...) (我知道上面的示例是解决问题的一种(非常!)糟糕的方法。我对这个问题的一般回答感兴趣,而不是特别是将罗马数字转换为整数...)
You can use locals
: 您可以使用
locals
:
s = 1
locals()['s']
EDIT: 编辑:
Actually, get
in R is more versatile - get('as.list')
will give you back as.list
. 实际上,R中的
get
更通用get('as.list')
将带您回到as.list
。 For class members, in Python, we can use getattr
( here ), and for built-in things like len
, getattr(__builtins__, 'len')
works. 对于类成员,在Python中,我们可以使用
getattr
( here ),对于诸如len
getattr(__builtins__, 'len')
可以使用。
Use the eval
function, which evaluates a string as an expression. 使用
eval
函数,该函数将字符串作为表达式求值。
X = 10
r = "XVI"
v = eval(r[0])
Important note: eval()
evaluates any code that can be used in an expression, not just variables. 重要说明:
eval()
评估表达式中可以使用的任何代码,而不仅仅是变量。 Do not use it directly in conjunction with user input, which could risk a security vulnerability. 不要将其与用户输入直接结合使用,否则可能会导致安全漏洞。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.