Hlelp clean up clumpsy code
Steven Bethard
steven.bethard at gmail.com
Tue Jan 4 04:45:49 EST 2005
It's me wrote:
> Another newbie question.
>
> There must be a cleaner way to do this in Python:
>
> #### section of C looking Python code ####
> a = [[1,5,2], 8, 4]
> a_list = {}
> i = 0
> for x in a:
> if isinstance(x, (int, long)):
> x = [x,]
> for w in [y for y in x]:
> i = i + 1
> a_list[w] = i
> print a_list
> #####
>
> The code prints what I want but it looks so "C-like". How can I make it
> more Python like?
Don't know what version of Python you're using, but if you're using 2.4
(or with a few slight modifications, with 2.3), you can write:
py> dict((item, i+1)
... for i, item in enumerate(
... a_sub_item
... for a_item in a
... for a_sub_item
... in isinstance(a_item, (int, long)) and [a_item] or a_item))
{8: 4, 1: 1, 2: 3, 4: 5, 5: 2}
Basically, I use a generator expression to flatten your list, and then
use enumerate to count the indices instead of keeping the i variable.
Steve
More information about the Python-list
mailing list