Python 遍历类对象列表,返回该对象不可iterable?
我有一门初级课程:Python 遍历类对象列表,返回该对象不可iterable?,python,python-3.x,class,Python,Python 3.x,Class,我有一门初级课程: class foo: def __init__(self, a, b): self.a = a self.b = b 以及另一个使用foo类的类: class bar: def __init__(self, foos): self.foos = sorted(foos, key=attrgetter('a')) 其中foos是foo的列表。现在,我想列出一个foo列表,如下所示: lofoos = [[foo
class foo:
def __init__(self, a, b):
self.a = a
self.b = b
以及另一个使用foo类的类:
class bar:
def __init__(self, foos):
self.foos = sorted(foos, key=attrgetter('a'))
其中foos是foo的列表。现在,我想列出一个foo列表,如下所示:
lofoos = [[foo1, foo2, foo3], [foo4, foo5, foo6] ...]
我想使用map函数来实现这一点:
list(map(lambda foos: bar(foos), lofoos))
但这会返回错误:
TypeError: iter() returned non-iterator of type 'foo'.
有没有一个简单的解决办法?问题是,你得到的是一个单子而不是一个单子,一个位置合适的打印件揭示了问题所在
from operator import attrgetter
class foo:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "{0.__class__.__name__}({0.a},{0.b})".format(self)
class bar:
def __init__(self, foos):
print("foos=",foos)
self.foos = sorted(foos, key=attrgetter('a'))
def __repr__(self):
return "{0.__class__.__name__}({0.foos})".format(self)
lofoos = [[foo(1,0), foo(2,0), foo(3,0)], [foo(4,1), foo(5,1), foo(6,1)]]
print("test list of lists of foo")
print(list(map(lambda foos: bar(foos), lofoos)))
print("\n")
print("test list of foo")
print(list(map(lambda foos: bar(foos), lofoos[0])))
输出
test list of lists of foo
foos= [foo(1,0), foo(2,0), foo(3,0)]
foos= [foo(4,1), foo(5,1), foo(6,1)]
[bar([foo(1,0), foo(2,0), foo(3,0)]), bar([foo(4,1), foo(5,1), foo(6,1)])]
test list of foo
foos= foo(1,0)
Traceback (most recent call last):
File "C:\Users\David\Documents\Python Scripts\stackoverflow_test.py", line 24, in <module>
print(list(map(lambda foos: bar(foos), lofoos[0])))
File "C:\Users\David\Documents\Python Scripts\stackoverflow_test.py", line 24, in <lambda>
print(list(map(lambda foos: bar(foos), lofoos[0])))
File "C:\Users\David\Documents\Python Scripts\stackoverflow_test.py", line 15, in __init__
self.foos = sorted(foos, key=attrgetter('a'))
TypeError: 'foo' object is not iterable
>>>
记住mapfun[a,b,c]所做的就是产生[funa,funb,func]
因此,在你的代码中的某个地方,你最终在一个foo列表中进行映射,而不是一个foo列表请给出一个完整的回溯。这很简单:foo不是迭代器。好的,有没有办法让bar成为迭代器?它对我有用…你的代码库中似乎有一个中断的iter实现。感谢测试,他们帮了很多忙才找到问题!