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 variableb = 0. - if every item in list has
a == 1, setb = 1. - if there mixture of
a == 0,a == 1in list, setb = 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
Post a Comment