SORU
28 Mayıs 2013, Salı


Nasıl bir liste ve tek bir truthy değer olup olmadığını kontrol edebilir miyim?

Python, olması gereken bir liste varbir ve tekdeğeri (bool(value) is True) truthy. Akıllı bir şekilde bunu kontrol etmek için var mı? Şu anda, sadece liste üzerinde yineleme ve elle kontrol ediyorum:

def only1(l)
    true_found = False
    for v in l:
        if v and not true_found:
            true_found=True
        elif v and true_found:
             return False #"Too Many Trues"
    return true_found

Bu çok kaba ve çok pythonic görünüyor. Zeki bunu yapmak için bir yol var mı?

CEVAP
28 Mayıs 2013, Salı


İthalat gerektirmez

def single_true(iterable):
    i = iter(iterable)
    return any(i) and not any(i)

Alternatif olarak, daha okunabilir bir sürümünü belki de:

def single_true(iterable):
    iterator = iter(iterable)
    has_true = any(iterator) # consume from "i" until first true or it's exhuasted
    has_another_true = any(iterator) # carry on consuming until another true value / exhausted
    return has_true and not has_another_true # True if exactly one true found

Bu:

  • Görünüyor i herhangi bir gerçek değeri vardır emin olun
  • Bu noktadan bakıldığında iterable diğer gerçek değeri yoktur emin olmak için devam ediyor

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

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • hytchme

    hytchme

    9 Mart 2014
  • MagicofRahat

    MagicofRahat

    13 Temmuz 2007
  • Roger Huffman

    Roger Huffma

    4 ŞUBAT 2007