开发者

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) ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜