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

  • Schmittastic Jr.

    Schmittastic

    19 Mart 2013
  • SRT Photoshop Tutorials

    SRT Photosho

    19 Aralık 2012
  • SuppressedStorm

    SuppressedSt

    11 AĞUSTOS 2013