python - Efficient way of counting True and False -


this may trivial problem, want learn more other more clever , efficient ways of solving it.

i have list of items , each item has property a value binary.

  • if every item in list has a == 0, set separate variable b = 0.
  • if every item in list has a == 1, set b = 1.
  • if there mixture of a == 0 , a == 1 in list, set b = 2.

i can use set keep track of types of a value, such if there 2 items in set after iterating through list, can set b = 2, whereas if there 1 item in set retrieve item (either 0 or 1) , use set b.

any better way?

i suggest using any , all. benefit of readability rather cleverness or efficiency. example:

>>> vals0 = [0, 0, 0, 0, 0] >>> vals1 = [1, 1, 1, 1, 1] >>> vals2 = [0, 1, 0, 1, 0] >>> def category(vals): ...     if all(vals): ...         return 1 ...     elif any(vals): ...         return 2 ...     else: ...         return 0 ...  >>> category(vals0) 0 >>> category(vals1) 1 >>> category(vals2) 2 

this can shortened bit if like:

>>> def category(vals): ...     return 1 if all(vals) else 2 if any(vals) else 0 ...  

this works can interpreted __nonzero__ (or __bool__ in python 3) having true or false value.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -