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

  • Bryan Smith

    Bryan Smith

    12 Mart 2006
  • Showtime

    Showtime

    21 HAZİRAN 2006
  • XxMinayaxX1

    XxMinayaxX1

    9 Mayıs 2012