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

问题描述 投票:1回答:2

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

python
2个回答
2
投票

您可以通过在copy(或locals())上调用globals()来创建本地varibals的副本,以搜索变量名称和值的键值对,然后使用生成的字典执行您想要的操作

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)

打电话给qazxsw poi给你一个解释:

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.


1
投票

搜索变量

在R中,[name for name in copy.copy(locals().keys()) if name.startswith('ABC')]做了两件事:

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

所以

ls(pattern=...)

这两种情况都可以通过搜索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'] 函数

不幸的是,您无法在Python中实现像ls(...)这样的函数来搜索ls(),因为只要您输入该函数,当前作用域就会丢失,并且您获得locals()的局部变量:

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
© www.soinside.com 2019 - 2024. All rights reserved.