(在Python 3.1中)
(有些与another question I asked有关,但是这个问题是关于迭代器已经用尽。)
# 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/规范的方式重写它?
此外,除了获得更多经验之外,我还可以采取哪些措施避免此类错误? (坦率地说,我不喜欢这种语言功能,因为这些类型的错误易于制造且难以捕获。)
最佳答案
您可以简单地通过调用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]