我想写一个函数,可以用同样的方式遍历 dict
和 list
,就像下面的代码。但是,它不起作用并归咎于 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 + ","
注意:此函数的输入是dict
或list
。这是一个假设。
这是错误消息:
File "./write-hole-collector.py", line 595, in constructResult
for (key,value) in iter :
TypeError: 'builtin_function_or_method' object is not iterable
最佳答案
您需要调用 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
那是因为通过不调用该方法,您正在尝试迭代不支持该操作的方法对象。
关于Python:同时迭代字典和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654360/