[Tutor] Appending to many lists with list comprehension
jfouhy@paradise.net.nz
jfouhy at paradise.net.nz
Tue May 3 06:31:24 CEST 2005
Quoting Bernard Lebel <3dbernard at gmail.com>:
> aList = [ [], [] ]
>
>
> # Iterate attributes of the top object
> for oAttribute in oObj.attributes:
>
> # Append to list 0 the attribute "type" of the current attribute
> aList[0].append( str(oAttribute.type) )
>
> # Append to list 1 the attribute "name" of the current attribute
> aList[1].append( str(oAttribute.name) )
>
> Instead of having two separate lists and a for loop, I'd like to perform
> a list comprehension that would do this all in one go, if this is
> doable.
You could do:
[(str(x.type), str(x.name)) for x in oObj.attributes]
This won't produce the same result as your code; it will give you a list of
pairs, rather than a pair of lists.
For a list of pairs, you could do it in two list comprehensions:
[[str(x.type) for x in oObj.attributes], [str(x.name) for x in oObj.attributes]]
Or you could do a bit of subtle magic with zip:
zip(*[(str(x.type), str(x.name)) for x in oObj.attributes])
Or maybe some bonus magic:
[[str(x.__dict__[y]) for y in dir(x) if not y.startswith('_')] for x in
oObj.attributes]
This will give you a list of lists, analogous to the list of tuples earlier. It
will grab all the attributes not starting with an _ (so it should avoid the
baggage all objects come with, but caution is still advised).
[is using __dict__ here the best way of doing this?]
Of course, you can unzip it as before:
zip(*[[str(x.__dict__[y]) for y in dir(x) if not y.startswith('_')] for x in
oObj.attributes])
HTH!
--
John.
More information about the Tutor
mailing list