[Tutor] Extending a list within a list comprehension

Victor Bouffier victor at grupocdm.com
Wed Apr 12 00:15:58 CEST 2006


Hi all,

I have solved my problem, but would like to know if what I accomplished
can be done with different data using list comprehensions.

the list I want to sort has the following format:

elements = [
(codigo, [ cant, importe, porc]),
(codigo, [ cant, importe, porc]),
...
]

Actual data is:
In [129]: elements[0:5]
Out[129]:
[('2712', [22.0, 3618.8099999999999, 0.0032389476163069883]),
 ('2713', [19.0, 6551.8100000000004, 0.0058640739309320719]),
 ('2710', [21.0, 2553.5799999999999, 0.0022855336019435113]),
 ('2716', [19.0, 8215.2700000000004, 0.0073529224203034461]),
 ('4305', [4.0, 348.37, 0.00031180199598565978])]


And I want to sort descending on 'importe', which is x[1][1] for x in
elements.

What I did was the following, following the Schwarzian Transform:

temporal = []
temporal = [ [x[1][1], (x[0], description[x[0]],
    x[1][0], x[1][1], x[1][2] ) ] for x in elements ]
temporal.sort()
temporal.reverse()          # sort descending
elements = [ x[1] for x in temporal ]

If the second element in each array passed as x is of variable length
(that is, it has a different element count than three, in this case),
the program needs to extend the list instead. Without list
comprehensions, and the added capability to utilize and sized list as a
second element, my code ended up looking like the following:

temporal = []
for x in elements:
    lst = [x[0], description[x[0]]]
    lst.extend(x[1])
    temporal.append([x[1][1], lst])
temporal.sort()
temporal.reverse()          # sort descending
elements = [ x[1] for x in temporal ]

Is there a way to use list comprehensions to append or extend the array
as needed by the second code listing?

Thanks.
Victor




More information about the Tutor mailing list