[Tutor] Extending a list within a list comprehension
victor at grupocdm.com
Wed Apr 12 07:17:35 CEST 2006
On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote:
> Victor Bouffier wrote:
> > 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, description[x]]
> > lst.extend(x)
> > temporal.append([x, lst])
> > temporal.sort()
> > temporal.reverse() # sort descending
> > elements = [ x 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?
> I think you are looking for
> temporal = [ [x, description[x]] + x for x in elements ]
I try this one and get the following error:
TypeError: list objects are unhashable
I figured it is because of the x element being used as a dict key.
Can you explain further where this error comes from? Are you getting it
> but I would make two steps, one for the sort using just
> [ (x, x) for x in elements ]
You are right. This is cleaner and not a big deal to do in two steps.
However for the issue at hand, it still keeps x as a two element list:
[codigo, [ cant, importe, porc]],
which I would like to have extended:
[codigo, cant, importe, porc]
It is not a big deal. That is why I finally went with the longer version
Alan suggested. Before the sort I get a two element list, the second
element being the list I finally want as output.
> then when you pick the data back out you can format it how you like.
Right. After the sort I just get that second element in another list
lines = [ x for x in temp ]
Thanks for your help.
> PS to John: the original solution is using DSU, aka Schwarzian Transform
> Tutor maillist - Tutor at python.org
More information about the Tutor