1

我正在尝试扫描字典引用列表以获取每个字典中的键数。我如何去引用一个元素的名称而不是字典的内容?audit_dicts 列表中的每个元素都是对现有字典的引用。

audit_dicts = [ osdata, weblogic, tomcat ]
for i in audit_dicts:
    print "Length of the %s dictionary is %d lines." % (i.name(), len(i))

我知道它与内容类型是字典有关,但是没有办法打印列表中元素的名称吗?我本质上是使用列表来存储所有这些字典,这样我就可以在一个循环中对它们执行多个操作。另外,有没有办法在同一个循环中声明这些字典?这样做的pythonic方式是什么?我目前有大约 20 种不同的数据字典,但在从 Web 数据构建字典之前,我只能对每个字典进行单独处理。

for i in audit_dicts:
    i = {}
4

2 回答 2

6

Lists don't contain names, they contain references to other objects. If you want to be able to use more than just an index to refer to the elements then you should use another data structure such as a dict.

于 2013-05-20T13:49:05.440 回答
0

__name__如果为此对象设置了属性,则可以使用属性:

audit_dicts = [ osdata, weblogic, tomcat ]
for i in audit_dicts:
  name = "unknown";
  try:
    if __name__ in i:
      name = i.__name__;
  except:
    pass
  print "Length of the %s dictionary is %d lines." % (name, len(i))

但你最好使用 dict 而不是 list:

audit_dicts = {
  "osdata":osdata, 
  "weblogic":weblogic, 
  "tomcat":tomcat
  }
for key in audit_dicts:
    print "Length of the %s dictionary is %d lines." % (key, len(audit_dicts[key]))
于 2013-05-20T13:57:37.053 回答