python按模式列出作品中的变量(Python等效于R ls(pattern =“ namepattern”)

时间:2018-07-27 10:09:33

标签: python

什么是python命令列出与特定模式匹配的当前worskpace中存在的所有变量?例如,列出工作区中以“ ABC”开头的所有现有变量/对象

2 个答案:

答案 0 :(得分:2)

您可以通过调用copy上的locals()(或globals())来创建局部变量的副本,以搜索变量名和值的键值对,然后执行以下操作您想要的结果字典

import copy
ABCD = 'woof' # create the name and value of our var
local_dict = copy.copy(locals()) # create a shallow copy of all local variables, you don't want to iterate through a constantly changing dict
for name, value in d.items():
    if name.startswith('ABC'):
         print(name, value)

打电话给help(locals),这很像个错误:

locals()
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

编辑:

以下是一个简短的oneliner,仅用于名称:  [name for name in copy.copy(locals().keys()) if name.startswith('ABC')]

答案 1 :(得分:1)

搜索变量

在R中,ls(pattern=...)做两件事:

  1. 如果在函数内部调用,它将搜索该函数的局部变量。
  2. 如果从顶层调用,它将搜索工作空间(所有全局)变量

如此

alpha <- 1.
animal <- "dog"
tool <- "wrench"

ls(pattern="^a.*")
# "alpha"  "animal"

myfunction <- function(){
    value <- 1
    ls(pattern="value")
}

myfunction()
# "value"

两种情况都可以在Python中通过搜索locals()来完成:

import re

alpha = 1.
animal = "dog"
tool = "wrench"

[x for x in locals() if re.match('^a.*', x)]
# ['alpha', 'animal']

def function():
    value = 1
    print([x for x in locals() if re.match('value', x)])

function()
# ['value']

编写ls(...)函数

不幸的是,您无法在Python中实现像ls()这样的通过locals()搜索的函数,因为一旦输入该函数,当前作用域就会丢失,并且您会获得{{1 }}:

ls()

要实现此目的,您需要明确搜索所有父框架本地的变量。可以使用def ls(pattern='.*'): return [x for x in locals() if re.match(pattern, x)] def function(): value = 1 print(ls()) function() # ['pattern'] <- This is actually in scope of `ls()`, not of `function()` ls() # ['pattern'] <- This is actually in scope of `ls()`, not in global scope 模块来完成此操作:

inspect