【问题标题】:how can I delete multiple variables without actually typing variables one by one?如何在不实际键入变量的情况下删除多个变量?
【发布时间】:2020-11-29 16:51:56
【问题描述】:

我定义了一个函数filtering()如下:

def filtering(given_indices, string):
    string = string.replace(" or "," | ").replace(" and "," & ").replace("-","_")
    tag_list = [i.strip("() ") for i in string.replace(" | ","`").replace(" & ","`").split("`")]
    for tag in tag_list:
        variable_name = tag
        globals()[variable_name] = Filter(given_indices, variable_name)
    return eval("({}).indices".format(string))

具有定义明确的类 Filter,其中包括运算符 & 和 |。 字符串 可以由多个标签、括号、两个运算符中的一个或两者组成。例如“中国和(山或山)”。运行此函数的结果是过滤索引,具有与 tag_list 中的 tag 一样多的变量。

我想要做的是添加删除由 for tag...globals()...variable_name) 生成的所有变量的代码(例如 chinamountain , mountains),以便在执行函数 filtering() 并获得返回的索引后不会留下任何变量。我该怎么做?


------------------------------------------ ----------------------
提供下面的整个代码以使事情更清楚

def wth(given_indices, tag):
    if "_" in tag:
        tag = tag.replace("_", "-")
    if tag.startswith("no_"):
        tag = tag[3:]
        return list(filter(lambda x: not tag in data_taglists[x], given_indices))
        # data_taglists is pre-given 
    else:
        return list(filter(lambda x: tag in data_taglists[x], given_indices))

class Filter:
    def __init__(self, given_indices, tag):
        self.given_indices = given_indices
        self.indices = wth(self.given_indices, tag)
    def __and__(self, other_tag_class):
        obj = Filter(self.given_indices, "")
        obj.indices = list(set(self.indices) & set(other_tag_class.indices))
        obj.indices.sort()
        return obj
    def __or__(self, other_tag_class):
        obj = Filter(self.given_indices, "")
        obj.indices = list(set(self.indices) | set(other_tag_class.indices))
        obj.indices.sort()
        return obj

def filtering(given_indices, string):
    string = string.replace(" or "," | ").replace(" and "," & ").replace("-","_")
    tag_list = [i.strip("() ") for i in string.replace(" | ","`").replace(" & ","`").split("`")]
    for name in tag_list:
        globals()[name] = Filter(given_indices, name)
    return eval("({}).indices".format(string))

# e.g.
data_taglists = [['sky', 'ocean', 'people', 'blue', 'clouds', 'korea'],
['sky', 'mountain', 'tree', 'morning', 'korea'],
['sky', 'tree', 'snow', 'footstep', 'usa'],
['forest', 'tree', 'insect', 'firefly', 'night', 'japan'],
['sky', 'tree', 'insect', 'sunlight', 'usa'],
['sky', 'building', 'people', 'road', 'car', 'china'],
['sky', 'tree', 'person', 'road','china']]

given_indices = range(len(data_taglists))
print(filtering(given_indices, "korea or usa"))
print(filtering(given_indices, "(usa or korea or japan) and (sky and tree) and no_insect)")
a = filtering(given_indices, "korea")
print(filtering(a, "usa")

我知道这可能看起来很糟糕,因为我只知道编码的基础知识。如果你能详细告诉我我可以改进的地方,我将不胜感激。

【问题讨论】:

  • 这是一个巨大的危险信号,表明您的代码设计不佳。动态创建/删除变量几乎没有充分的理由
  • 为什么您的filtering 函数首先创建全局变量?只是不要创建它们。没有必要。更不需要eval
  • 我怎样才能得到相同结果的修复代码呢?你能详细描述一下吗?

标签: python filter global-variables filtering


【解决方案1】:

您可以使用 del 删除个人姓名:del variable_name

您可以通过查找 globals() 对象来删除任何变量

for name in dir():
    print(name)
    if not name.startswith('_'): # variables starting with an _ are internal variables
        del globals()[name]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多