[Python-ideas] dict.fromkeys() better as dict().setkeys() ? (and other suggestions)

Ron Adam rrr at ronadam.com
Wed May 30 04:12:56 CEST 2007


Jim Jewett wrote:
> On 5/29/07, Josiah Carlson <jcarlson at uci.edu> wrote:
>> Ron Adam <rrr at ronadam.com> wrote:
>> > Josiah Carlson wrote:

> *this* is the core of a useful idea.  list (and set and generator)
> comprehensions can't partition very well, because they have only a
> single output.  There isn't a good way to say:
> 
>    list_a = [x for x in src if pred(a)]
>    src = [x for x in src if not pred(a)]
>    list_b = [x for x in src if pred(b)]
>    src = [x for x in src if not pred(b)]
>    list_c = [x for x in src if pred(c)]
>    list_other = [x for x in src if not pred(c)]
> 
> On the other hand, you can do it (inefficiently) as above, or you can
> write an (ugly) version using a custom function, so the solution would
> have to be pretty good before it justified complicating the
> comprehension APIs.

I can't see how it could be done with out as you say... complicating the 
comprehension APIs.

However, I do think there could be very useful uses for a standard sorting 
structure of some sort.  That's the sorting as in mail sorters, or category 
sorters, that produce several streams of output instead of just one.

Would that be called a de-comprehension?

Mabye something like the following as a starting point?




# generate some random data

import random
import string

def random_pnum(length):
     ok_digits = string.letters + string.digits
     digits = [random.choice(ok_digits) for n in range(length)]
     return ''.join(digits)

src = []
for x in range(10):
     src.append(random_pnum(10))


# A de - comprehension generator

def decomp(seq, *cmps):
    results = dict(((c.__name__, []) for c in cmps))
    rest = []
    for x in seq:
       for c in cmps:
          if c(x):
              results[c.__name__].append(x)
              break
       else:
          rest.append(x)
    for c in cmps:
       yield results[c.__name__]
    yield rest


# Tests

def a_g(s):
    return s[0].lower() in "abcdefg"

def h_m(s):
    return s[0].lower() in "hijklm"

def n_z(s):
    return s[0].lower() in "nopqrstuvwxyz"

decmps = [a_g, h_m, n_z]
ag, hm, nz, other = decomp(src, *decmps)

print 'ag =', ag
print 'hm =', hm
print 'nz =', nz
print 'other =', other


-------------------

ag = ['c8WQe60G6J', 'EMY7O8qzTg']
hm = ['lDunyeOM98', 'LJuPg8ncZd']
nz = ['uhhuhd9YdO', 'qAuQvfTc6N', 'vpJz47pkP5', 'YOq6m4IXBn']
other = ['8JE6PuXxBz', '4ttyMdpuQY']




More information about the Python-ideas mailing list