Python:删除除循环变量以外的所有变量,且无污染 [英] Python: delete all variables except one for loops without contaminations

查看:395
本文介绍了Python:删除除循环变量以外的所有变量,且无污染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

%reset
%reset -f

%reset_selective a
%reset_selective -f a

是Matlab命令全部清除"的Python替代方法,其中"-f"表示无需确认就强制使用","_ selective"可以与

are usefull Python alternative to the Matlab command "clear all", in which "-f" means "force without asking for confirmation" and "_selective" could be used in conjunction with

who_ls

选择性地删除工作区中的变量,如此处 https://ipython所示. org/ipython-doc/3/interactive/magics.html .

to selectively delete variables in workspace as clearly shown here https://ipython.org/ipython-doc/3/interactive/magics.html .

现在,我正在管理要定义大量变量的循环,例如

Now I am managing loops in which I am going to define a large number of variables, for example

for j in range(1000):
    a = crazy_function1()
    b = crazy_function2()
    ...
    m = crazy_function18()
    n = crazy_function19()
    ...
    z = crazy_functionN()

,在每个循环的最后,我想删除所有变量,除了Python工作区的标准变量和我介绍的一些变量(在此示例中,只有m和n).这样可以避免污染和内存负担,从而使代码更高效,更安全.

and at the end of each cycle I want to delete ALL variables EXCEPT the standard variables of the Python workspace and some of the variables I introduced (in this example only m and n). This would avoid contaminations and memory burdening hence it will make the code more efficient and safe.

我看到"who_ls"结果看起来像一个列表,因此我想在循环中删除所有不等于m或n的变量

I saw that "who_ls" result looks like a list, hence I thought at a loop that delete all variables that are not equal to m or n

for j in range(1000):
    a = crazy_function1()
    b = crazy_function2()
    ...
    m = crazy_function18()
    n = crazy_function19()
    ...
    z = crazy_functionN()
    if who_ls[j] != m or who_ls[j] != n:
         %reset_selective -f who_ls[j]

,但是它不起作用,因为who_ls看起来像一个列表,但是却不起作用.您将如何修改代码的最后几行? 有什么类似的东西

but it doesn't work as who_ls looks as a list but it doesn't work as a list. How would you modify the last lines of code? Is there anything like

 %reset_selective -f, except variables(m, n)

?

推荐答案

限制变量范围的通常方法是在函数中使用它们.完成该功能后,其locals消失.

The normal approach to limiting the scope of variables is to use them in a function. When the function is done, its locals disappear.

In [71]: def foo():
    ...:     a=1
    ...:     b=2
    ...:     c=[1,2,3]
    ...:     d=np.arange(12)
    ...:     print(locals())
    ...:     del(a,b,c)
    ...:     print(locals())
    ...:     
In [72]: foo()
{'d': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]), 'c': [1, 2, 3], 'a': 1, 'b': 2}
{'d': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])}

=================

==================

%who_ls返回一个列表,并且可以在RHS上使用,如

%who_ls returns a list, and can be used on the RHS, as in

xx = %who_ls

,然后可以迭代该列表.但是请注意,这是变量名称的列表,而不是变量本身.

and then that list can be iterated. But note that this is a list of variable names, not the variables themselves.

for x in xx: 
    if len(x)==1:
        print(x)
        # del(x)  does not work

显示所有长度为1的名称.

shows all names of length 1.

=====================

======================

使用%reset_selective的一种简单方法是为临时变量赋予一个独特的名称,例如regex可以轻松找到的前缀.例如

A simple way to use %reset_selective is to give the temporary variables a distinctive name, such as a prefix that regex can easily find. For example

In [198]: temp_a, temp_b, temp_c, x, y = 1,'one string',np.arange(10), 10, [1,23]
In [199]: who_ls
Out[199]: ['np', 'temp_a', 'temp_b', 'temp_c', 'x', 'y']
In [200]: %reset_selective -f temp 
In [201]: who_ls
Out[201]: ['np', 'x', 'y']

===================

====================

这是从名称列表中进行此删除的示例.请记住,我们要删除的实际变量与其名称之间存在差异.

Here's an example of doing this deletion from a list of names. Keep in mind that there is a difference between the actual variable that we are trying to delete, and its name.

添加一些变量以及要删除的名称列表

Make some variables, and list of names to delete

In [221]: temp_a, temp_b, temp_c, x, y = 1,'one string',np.arange(10), 10, [1,23]
In [222]: dellist=['temp_a', 'temp_c','x']

获取外壳,然后获取user_ns. who_ls使用self.shell.user_ns中的键.

Get the shell, and the user_ns. who_ls uses the keys from self.shell.user_ns.

In [223]: ip=get_ipython()
In [224]: user_ns=ip.user_ns

In [225]: %who_ls
Out[225]: ['dellist', 'i', 'ip', 'np', 'temp_a', 'temp_b', 'temp_c', 'user_ns', 'x', 'y']

In [226]: for i in dellist:
     ...:     del(user_ns[i])
     ...:     
In [227]: %who_ls
Out[227]: ['dellist', 'i', 'ip', 'np', 'temp_b', 'user_ns', 'y']

因此,我们必须在user_ns词典中查找名称才能删除它们.请注意,此删除代码创建了一些变量dellistiipuser_ns.

So we have to look up the names in the user_ns dictionary in order to delete them. Note that this deletion code creates some variables, dellist, i, ip, user_ns.

==============

==============

您担心多少个变量?他们多大?标量,列表,numpy数组.一打可以用字母命名的标量不会占用太多内存.而且,如果在变量的生成中有任何模式,那么将它们收集在列表或字典中可能更有意义,而不是尝试为每个变量赋予唯一的名称.

How many variables are you worried about? How big are they? Scalars, lists, numpy arrays. A dozen or so scalars that can be named with letters don't take up much memory. And if there's any pattern in the generation of the variables, it may make more sense to collect them in a list or dictionary, rather than trying to give each a unique name.

通常,最好使用函数来限制变量的范围,而不是使用del()%reset.有时,如果要处理非常大的数组(这种数组占用大量内存并可能产生内存错误),我可以使用del或仅使用a=None删除它们.但是普通变量不需要特别注意(即使在ipython持续数天的会议中也是如此).

In general it is better to use functions to limit the scope of variables, rather than use del() or %reset. Occasionally if dealing with very large arrays, the kind that take a meg of memory and can create memory errors, I may use del or just a=None to remove them. But ordinary variables don't need special attention (not even in an ipython session that hangs around for several days).

这篇关于Python:删除除循环变量以外的所有变量,且无污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆