simultaneous assignment

Steve R. Hastings steve at hastings.org
Wed May 3 21:30:27 CEST 2006


On Wed, 03 May 2006 17:51:03 +0000, Edward Elliott wrote:

> Steve R. Hastings wrote:
>> You could also use a function that counts all different values in a list,
>> reducing the list to a dictionary whose keys are the unique values from
>> the list. 
> 
> Wouldn't reducing to a set instead of a dict make more sense if all you want
> to do is count uniq elements?

My apologies for not explaining tally() better.

The dict has one key for each unique element, and the value associated
with each key is a count of how many times that element appeared in the
original list.

lst = ['a', 'b', 'b', 'c', 'c', 'c']
d = iterwrap.tally(lst)
print d  # prints something like: {'a': 1, 'c': 3, 'b': 2}


If you didn't care how many times the values appeared in the original
list, and just just wanted the unique values, then a set would be perfect.

If you happen to have tally(), it is an easy way to solve the original
problem: figure out whether a list has exactly one true value in it.

d = tally(bool(x) for x in lst)
if d[True] == 1:
    print "and there was much rejoicing"

-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list