一尘不染

精疲力尽的迭代器-该怎么办?

python

trying to see the ratio of the max and min element in a container c

filtered = filter(lambda x : x is not None and x != 0, c)
ratio = max(filtered) / min(filtered)

我花了半个小时才意识到问题出在哪里(过滤器返回的迭代器在到达第二个函数调用时已经耗尽了)。如何以最Pythonic /规范的方式重写它?

另外,除了获得更多经验之外,我还可以采取哪些措施避免此类错误?(坦率地说,我不喜欢这种语言功能,因为这些类型的错误易于制造且难以捕获。)


阅读 129

收藏
2020-12-20

共1个答案

一尘不染

您可以简单地通过调用将迭代器转换为元组 tuple(iterator)

但是我会将该过滤器重写为列表理解,看起来像这样

# original
filtered = filter(lambda x : x is not None and x != 0, c)

# list comp
filtered = [x for x in c if x is not None and x != 0]
2020-12-20