# list of tuples with dynamic change in position

Gerard Flanagan grflanagan at gmail.com
Tue Sep 7 09:47:48 CEST 2010

```On 7 Sep, 07:42, sajuptpm <sajup... at gmail.com> wrote:
> More details
> I have a list of tuples l = [((cpu_util,mem_util),(disk_util)),
> ((cpu_util,mem_util),(disk_util))]
> ie, l = [((30,50),(70)), ((50,20),(20))]
>
> l.sort(key=lambda x:(-x[0][0], x[1][0])) # sorting cpu_util asc and
> disk_util desc
>
> suppose i changed order that is l = [((mem_util,cpu_util),
> (disk_util)), ((mem_util,cpu_util),(disk_util))]
> So i have to change the sort code to l.sort(key=lambda x:(-x[0][1],
> x[1][0])) # sorting cpu_util asc and disk_util desc
>
> I want to use same (common) sort code, that must work even if i
> changed tuple order.

If you have a sort function that works just leave it as it is and
rearrange your data before passing it to the sort function. Eg.

----------------------------------
d1 = [
((30,50),(90,)),
((30,50),(70,)),
((50,20),(20,)),
((20,20),(50,)),
((20,20),(60,)),
((20,20),(10,)),
]

d2 = [
((50,30),(90,)),
((50,30),(70,)),
((20,50),(20,)),
((20,20),(50,)),
((20,20),(60,)),
((20,20),(10,)),
]

def _sort_the_tuples(iterable):
#print list(iterable)
return sorted(iterable, key=lambda t: (-t[0][0], t[1][0]))

def sort_the_tuples(iterable, rearrange=lambda X: X):
return _sort_the_tuples(rearrange(t) for t in iterable)

assert sort_the_tuples(d1) == \
sort_the_tuples(d2, lambda X: ((X[0][1], X[0][0]), (X[1][0],)))

--------------------------------

The point of my previous response was to deal with a list of
dictionaries and sort by attribute rather than index, but whatever
works.

Regards

```