On Sat, 01 Apr 2006 00:38:08 -0800, Steve R. Hastings wrote: > my proposed truecount() returns a tuple, with the length and > the count of true values.
I never liked the name truecount(), and the more I think about it, the less I like the function. It should either solve a very important need, or else it should be general enough to solve multiple needs; truecount() doesn't really do either. I kept thinking about this, and then suddenly I remembered an idea I read about before. I'm not sure who invented this idea, but it wasn't me. Here is a function called "tally()". It reduces a list to a dictionary of counts, with one key for each value from the list. The value for each key is the count of how many times it appeared in the list. def tally(seq, d=None): if d == None: d = {} for x in seq: if x in d: d[x] += 1 else: d[x] = 1 return d This neatly replaces truecount(), and you can use it for other things as well. Let's revisit my example from before: > Suppose you wanted, for some reason, to know how many lines in a file > start with a vowel: vowels = frozenset("aeiouAEIOU") f = open("a_file.txt") # note that f is an iterator counts = tally(line[0] in vowels for line in f) # counts is a dict; counts.keys() == [False, True] count_nonvowels, count_vowels = counts.values() total = count_nonvowels + count_vowels print "%d lines in file; %d start with a vowel" % (total, count_vowels) -- Steve R. Hastings "Vita est" [EMAIL PROTECTED] http://www.blarg.net/~steveha -- http://mail.python.org/mailman/listinfo/python-list