【问题标题】:Python: Iterate over dict and list at the same timePython:同时迭代 dict 和 list
【发布时间】:2023-10-26 06:31:01
【问题描述】:

我想写一个函数,可以用同样的方式迭代dictlist,就像下面的代码。但是,它不起作用并指责iter 不是迭代器。

def constructResult(*args):
    header = ''
    result = ''
    for arg in args :
        if isinstance(arg, dict) :
            iter = arg.items; #arg is a dict
        else:
            iter = arg #arg is a list 
        for (key,value) in iter :
            header = header + key + ","

注意:此函数的输入是dictlist。这是一个假设。

这是错误信息:

 File "./write-hole-collector.py", line 595, in constructResult
   for (key,value) in iter :
 TypeError: 'builtin_function_or_method' object is not iterable

【问题讨论】:

  • 列表是否也会有两个元素元组?
  • 旁白:iter 是方便的 built-in function 的名称,因此对于您自己的变量之一来说不是一个好名称。
  • 是的。事实上,当我有两个函数分别处理 list 和 dict 时,它就起作用了。

标签: python list dictionary


【解决方案1】:

你需要调用dict.items()方法:

iter = arg.items()  #arg is a dict

否则你确实会得到一个异常,告诉你方法本身不可迭代:

>>> d = {}
>>> for key, value in d.items:  # not called
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not iterable

那是因为不调用方法,你是在尝试迭代方法对象,它不支持该操作。

【讨论】:

    【解决方案2】:

    for key in z.keys(): print(key)

    在一个函数上的迭代器不是变量。代替 Keys 尝试使用 keys()

    【讨论】:

      最近更新 更多