How do you modify the elements of a list in Python?


I have this code and I want to know how to append the list so I can sort it by number, high to low

data=['red' '1', 'blue' '8', 'green' '2', 'orange' '6']

I would like to know how to sort the list by the number from high to low by changing the items in the list so the number is before the colour so it can simply be sorted from high to low.

Here is how the list should be:

data=['1' 'red', '8' 'blue', '2' 'green' ,'6' 'orange']

If you actually have 8 separate items and want to sort by numbers from high to low you can group them using iter, reversing the order:

data=['red', '1', 'blue', '8', 'green' ,'2', 'orange','6']

from itertools import chain
it = iter(data)
grouped = zip(it, it)

data = sorted(((b, a) for a,b in grouped),
          key=lambda x: int(x[0]),reverse=True))

['8', 'blue', '2', 'green', '1', 'red']

But you my be better off keeping the elements in tuples:


[('8', 'blue'), ('2', 'green'), ('1', 'red')]

If your data is actually as posted use itertools to create pairings, ad actually sorting correctly casting the digits to int:

from itertools import dropwhile as dw, takewhile as tw
data=['red' '1', 'blue' '8', 'green' '2', 'orange' '6']
data = sorted((("".join(dw(str.isalpha,s)), "".join(tw(str.isalpha,s)))
               for s in data),key=lambda x: int(x[0]),reverse=True)
[('8', 'blue'), ('6', 'orange'), ('2', 'green'), ('1', 'red')]

Or rejoin as strings:

print(["".join(tup) for tup in data])
['8blue', '2green', '1red']