问题描述
(在 Python 3.1 中)(与我问的另一个问题有些相关,但这个问题是关于迭代器被耗尽.)
(In Python 3.1)(Somewhat related to another question I asked, but this question is about iterators being exhausted.)
# 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)
我花了半个小时才意识到问题所在(filter 返回的迭代器在到达第二个函数调用时已耗尽).我如何以最 Pythonic/规范的方式重写它?
It took me half hour to realize what the problem is (the iterator returned by filter is exhausted by the time it gets to the second function call). How do I rewrite it in the most Pythonic / canonical way?
此外,除了获得更多经验之外,我还能做些什么来避免此类错误?(坦白说,我不喜欢这个语言特性,因为这些类型的错误很容易产生,很难发现.)
Also, what can I do to avoid bugs of this sort, besides getting more experience? (Frankly, I don't like this language feature, since these types of bugs are easy to make and hard to catch.)
推荐答案
只需调用 tuple(iterator)
但是我会将该过滤器重写为列表推导式,看起来像这样
however I'd rewrite that filter as a list comprehension, which would look something like this
# 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]
这篇关于用尽的迭代器——如何处理它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!