2016-12-30 80 views
-3

我有一個初始等級:遍歷類對象列表的列表,返回該對象不可迭代?

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')) 

其中foosfoo列表。我現在想採取的foo名單列表,這東西看起來像:

lofoos = [[foo1, foo2, foo3], [foo4, foo5, foo6] ...] 

,我想使用地圖功能來做到這一點:

list(map(lambda foos: bar(foos), lofoos)) 

但這返回錯誤:

TypeError: iter() returned non-iterator of type 'foo'. 

有沒有簡單的解決方案呢?

+0

的目錄列表做一個地圖,請給出[MCVE]與完整的回溯。 – jonrsharpe

+0

這很簡單:'foo'不是迭代器。 – 2016-12-30 19:59:45

+0

好的,有沒有辦法讓bar成爲迭代器? –

回答

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

+0

謝謝你的測試中,他們幫助了很多在發現問題! –