如何使用循环获取dir()中的值? [英] how to use loop to get values in dir()?

查看:165
本文介绍了如何使用循环获取dir()中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法使用循环中的项目获取dir()中的项目中的值:

 
打印(项目)

只打印

  __builtins__ 
__doc__
__loader__
__name__
__package__
__spec__
__ main __
__ name __
谢谢!

解决方案

一个href =https://docs.python.org/3/library/functions.html#dir =nofollow> dir 没有参数在逻辑上相当于 list(locals()),在获取当前命名空间中的变量名称( locals()字典)。



您将使用项目方法 localals()替代:

 在[5]中:列表中的值(locals()。items()):
...: print(name,value)
...:


Why i can't get the values in the items in dir() with loop:

for item in dir():
    print(item)

It just print

 __builtins__
 __doc__
 __loader__
 __name__
 __package__
 __spec__

So, how can i use loop to print the value in item, i.e "__main__" in __name__ Thanks!

解决方案

Calling dir without the argument is logically equivalent to list(locals()), as in getting the list of names of variables in the current namespace (keys of locals() dictionary).

You'd use the items method of locals() instead:

In [5]: for name, value in list(locals().items()):
   ...:     print(name, value)
   ...: 

这篇关于如何使用循环获取dir()中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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