简体   繁体   中英

Pythonic way to set sort order?

I have a collection on objects that I need to assign a random order. I wrote a pretty dumb java style loop to do it, but what is a fancier pythonic way to achieve the same?

from random import shuffle

class pair(object):
    def __init__(self, name):
        self.name = name
        self.order = 0
    def __repr__(self):
        return self.name + " order: " + str(self.order)

test =[pair('a'),pair('b'),pair('c'),pair('d')]
print(test)
#shuffle the list
shuffle(test)
i = 1
#this is what i want to replace <------
for t in test:
    t.order=i
    i+=1

print(test)

Sample output:

>>>[a order: 0, b order: 0, c order: 0, d order: 0]
>>>[c order: 1, a order: 2, d order: 3, b order: 4]

This isn't a lot simpler than yours, but it's perhaps a little bit neater:

for i, t in enumerate(test):
    t.order = i
[ x.order = o for o, x in enumerate(test) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM