首页 文章

Python中R的ls()函数的等价物,用于删除所有创建的对象

提问于
浏览
-1

我是Python新手 . R中有一个名为 ls() 的函数 . 我可以使用 ls()rm() 函数轻松删除任何创建的对象 .

R Code

# Create x and y
x = 1
y = "a"

# remove all created objects
ls()
# [1] "x" "y"
rm(list = ls())

# Try to print x
x
# Error: object 'x' not found

this帖子中有人在python中提出了相当于 ls() 的内容 . 所以,我试图在python中做同样的操作 .

Python Code

# Create x and y
x = 1
y = "a"

# remove all created objects
for v in dir(): del globals()[v]

# Try to print x
x
# NameError: name 'x' is not defined

但问题是当 x 被重新创建并打印时它会抛出错误:

# Recreate x
x = 1

# Try to print x
x

回溯(最近一次调用最后一次):文件“”,第1行,在x文件“C:\ SomePath \ Anaconda \ lib \ site-packages \ IPython \ core \ displayhook.py”,第258行,调用self.update_user_ns (结果)文件“C:\ SomePath \ Anaconda \ lib \ site-packages \ IPython \ core \ displayhook.py”,第196行,在update_user_ns中,如果结果不是self.shell.user_ns ['_ oh']:KeyError:' _哦'

我注意到 dir() 除了我的对象之外还提供了一些额外的对象 . 是否有任何函数可以提供与R的 ls() 相同的输出?

2 回答

  • 3

    这里有不同的问题 .

    这段代码是否正确?

    # remove all created objects
    for v in dir(): del globals()[v]
    

    不它不是!首先 dir() 从本地映射返回键 . 在模块级别,它与 globals() 相同,但不在函数内部 . 接下来它包含一些你不想删除的对象,如 __builtins__ ...

    是否有任何函数可以提供与R的ls()相同的输出?

    不完全是,但你可以尝试用类来模仿它:

    class Cleaner:
        def __init__(self):
            self.reset()
        def reset(self):
            self.keep = set(globals());
        def clean(self):
            g = list(globals())
            for __i in g:
                if __i not in self.keep:
                    # print("Removing", __i)      # uncomment for tracing what happens
                    del globals()[__i]
    

    创建清理对象时,它会保留所有预先存在的对象的列表(更确切地说是 set 对象) . 当你调用它的 clean 方法时,它会从 globals() 映射中删除自创建以来添加的所有对象(包括它自己!)

    示例(带有未注释的跟踪):

    >>> class Cleaner:
        def __init__(self):
            self.reset()
        def reset(self):
            self.keep = set(globals());
        def clean(self):
            g = list(globals())
            for __i in g:
                if __i not in self.keep:
                    print("Removing", __i)      # uncomment for tracing what happens
                    del globals()[__i]
    
    
    >>> dir()
    ['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
    >>> c = Cleaner()
    >>> i = 1 + 2
    >>> import sys
    >>> dir()
    ['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'c', 'i', 'sys']
    >>> c.clean()
    Removing c
    Removing i
    Removing sys
    >>> dir()
    ['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
    
  • 0

    根据@Arihant的评论,我试过:

    zzz = %who_ls
    for v in zzz : del globals()[v]
    del v,zzz
    

    我希望这可以在一行中完成 . 欢迎任何建议 .

    另一个类似的解决方案

    %reset -f
    

相关问题