list of tuples with dynamic change in position

sajuptpm sajuptpm at gmail.com
Tue Sep 7 07:22:08 EDT 2010


On Sep 7, 1:16 pm, Ulrich Eckhardt <eckha... at satorlaser.com> wrote:
> sajuptpm wrote:
> > 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
>
> One thing here: Without knowing what special meaning the indices have, this
> code is impossible to understand. In my opinion, that code should rather be
>
>   l.sort(key=lambda x: (-x.cpu_util, x.disk_util))
>
> You could then save the comment, which btw may or may not describe the
> actual code.
>
> > 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.
>
> You don't have to use a lambda function. You can as well define the sorting
> order in the same place of your code where you define the order inside the
> elements, that way you would only have to adjust the sorting in one place.
>
> Otherwise, you will have to embed the order of the tuple inside the tuple or
> the containing list. One approach would be to have a dictionary (which has
> no order), or you use a separate type instead:
>
>   class record(object):
>       pass
>
>   r = record()
>   r.cpu_util = 12
>   r.disk_util = 42
>   l.append(r)
>
> However, this basically all boils down to either "don't use the sorting
> (dict)" or "keep records sorted", so it doesn't really answer your
> question. However, I'm afraid there is no answer to your question as it
> stands. Maybe I could help you better if you explained why the order
> changes etc, because normally I don't deal with data that has such a
> volatile meaning, I rather normalize it on input and then use it in the
> same way afterwards.
>
> Uli
>
> --
> Sator Laser GmbH
> Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932



[((cpu_util,mem_util),(disk_util)),((cpu_util,mem_util),(disk_util))]

i want to find the loaded machine based on cpu and mem and desk
utilization by changing this order.

I created a UI using that i can change the order of item in the tuple.
But the problem is asc and desc sorting






More information about the Python-list mailing list