我有一个初级课程:
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'.
有一个简单的解决方案吗?
答案 0 :(得分:0)
问题在于,您获得了bar
个人foo
而不是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
>>>
请记住map(fun,[a,b,c])
所做的是[fun(a),fun(b),fun(c)]
因此,在代码中的某个位置,您最终会在foo
列表中执行地图,而不是foo