exhausted iterators - what to do about them?

前端 未结 4 1000
庸人自扰
庸人自扰 2020-11-29 12:27

(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 an         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 13:14

    Actually your code raises an exception that would prevent this problem! So I guess the problem was that you masked the exception?

    >>> min([])
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: min() arg is an empty sequence
    >>> min(x for x in ())
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: min() arg is an empty sequence
    

    Anyways, you can also write a new function to give you the min and max at the same time:

    def minmax( seq ):
        " returns the `(min, max)` of sequence `seq`"
        it = iter(seq)
        try:
            min = max = next(it)
        except StopIteration:
            raise ValueError('arg is an empty sequence')
        for item in it:
            if item < min:
                min = item
            elif item > max:
                max = item
        return min, max
    

提交回复
热议问题