A really bad idea.
Tim Peters
tim.one at comcast.net
Fri Nov 15 12:50:39 EST 2002
[Dave Brueck]
> It's funny what people do and don't find readable, huh? I use list
> comps all the time because to me they are almost always more readable
> than the equivalent code and more vertically compact as well. I
> wouldn't mind having a dictionary comp
Do you know that dict() accepts an iterable object producing iterable
objects producing 2 objects each? It's not exactly transparent when phrased
that way <wink>, but an example should help:
>>> dict([(i, i**2) for i in range(0, 20, 2)])
{0: 0, 16: 256, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100, 12: 144,
18: 324, 14: 196}
>>>
Or, more strangely,
>>> def square(i):
... yield i
... yield i**2
>>> dict([square(i) for i in range(0, 20, 2)])
{0: 0, 16: 256, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100, 12: 144, 18: 324, 14:
196}
>>>
dict(zip(keys, values)) is also a useful thing to understand.
> but don't need it nearly as much, even less so a generator comp.
waiting-for-someone-to-ask-for-class-comprehensions-ly y'rs - tim
More information about the Python-list
mailing list