SORU
19 Mart 2009, PERŞEMBE


Nasıl bir jeneratör baştan boş olup olmadığını nasıl anlayacağım?

Eğer jeneratör hiçbir öğe, peek, hasNext, ısempty, bu satırlar boyunca bir şey gibi varsa test basit bir yolu var mı?

CEVAP
19 Mart 2009, PERŞEMBE


Öneri:

def peek(iterable):
    try:
        first = next(iterable)
    except StopIteration:
        return None
    return first, itertools.chain([first], iterable)

Kullanımı:

res = peek(mysequence)
if res is None:
    # sequence is empty.  Do stuff.
else:
    first, mysequence = res
    # Do something with first, maybe?
    # Then iterate over the sequence:
    for element in mysequence:
        # etc.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Maschine Tutorials

    Maschine Tut

    15 ŞUBAT 2011
  • spectragirlz16's channel

    spectragirlz

    22 Ocak 2012
  • Vintendo Power

    Vintendo Pow

    2 Ocak 2007