Noah wrote: > I have a list of tuples > [('a', 1.0), ('b', 2.0), ('c', 3.0)] > I want to reverse the order of the elements inside the tuples. > [(1.0,'a'), (2.0, 'b'), (3.0, 'c')] > > I know I could do this long-form: > q = [] > y = [('a', 1.0), ('b', 2.0), ('c', 3.0)] > for i in y: > t=list(t) > t.reverse() > q.append(tuple(t)) > y = q > > But it seems like there should be a clever way to do this with > a list comprehensions. Problem is I can't see how to apply > reverse() to each tuple in the list because reverse() a > list method (not a tuple method) and because it operates > in-place (does not return a value). This kind of wrecks doing > it in a list comprehension. What I'd like to say is something like > this: > y = [t.reverse() for t in y] > Even if reverse worked on tuples, it wouldn't work inside a > list comprehension. > > Yours, > Noah >
Provided the data remains the same [(a, b), ...] Python 2.5a2 (r25a2:45740, May 24 2006, 19:50:20) [GCC 3.3.6] on linux2 >>> x = [('a', 1.0), ('b', 2.0), ('c', 3.0)] >>> y = [(b, a) for a, b in x] >>> y [(1.0, 'a'), (2.0, 'b'), (3.0, 'c')] Hope this helps, Adonis -- http://mail.python.org/mailman/listinfo/python-list