【问题标题】:Iterating through list of lists of class objects, returns that object is not iterable?遍历类对象列表,返回该对象不可迭代?
【发布时间】:2016-12-30 19:56:48
【问题描述】:

我有一个初始课程:

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

有没有简单的解决方案?

【问题讨论】:

  • 请给minimal reproducible example提供完整的回溯。
  • 很简单:foo 不是迭代器。
  • 好的,有没有办法让 bar 成为迭代器?
  • 它对我有用...
  • 您的代码库中似乎有一个损坏的__iter__ 实现。

标签: python python-3.x class


【解决方案1】:

问题是你得到了bar 个人foo 而不是foos 的列表,一个放置良好的打印揭示了问题

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 列表中进行映射

【讨论】:

  • 感谢您的测试,他们对发现问题有很大帮助!
猜你喜欢
  • 2014-02-08
  • 2021-04-25
  • 2015-08-24
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
相关资源
最近更新 更多