开发者

complex sorting on python ,very trivial but interesting bug

I wanted to sort with 'sets' or 'a'. I try with the information below .

>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

http://wiki.python.org/moin/HowTo/Sorting/

That function works with 'count' but not with 'sets', 'a'.

class Number:
    def __init__(self, sets, count, a):
        self.sets = sets
        self.cou开发者_JS百科nt = count
        self.a = a
    def __repr__(self):
        return repr((self.sets, self.count, self.a))


number_object=[([1, 3, 7], 2, 3), ([3, 7], 2, 2), ([2, 4], 2, 2), ([1, 7], 9, 2), ([1, 3], 2, 2), (7, 2, 0), (4, 2, 0), (3, 3, 0), (2, 2, 0), (1, 2, 0)]

I wanted to use the one below, but it doesn't work. I use the same way the webpage introduce.

sorted(student_objects, key=attrgetter('sets', 'count'))

Funny thing is that count can work, but not the other one.

After trying several time, I decide to use another way. I can get the same result with this instruction.

s=sorted(number_object, key=itemgetter(0), reverse=True )
sorted(s, key=itemgetter(1), reverse=True )

But I am curious why the original one doesn't work. is there anyone who is good at python??


If you follow the link you gave, you will realize you must instantiate your objects like this:

number_objects = [Number([1, 3, 7], 2, 3),
                  Number([3, 7], 2, 2), 
                  .......
                 ]

then,

sorted(number_objects, key=attrgetter('sets', 'count'))

should work.

For example:

from operator import attrgetter
class Number:
    def __init__(self, sets, count, a):
        self.sets = sets
        self.count = count
        self.a = a
    def __repr__(self):
        return repr((self.sets, self.count, self.a))


number_objects = [Number([1, 3, 7], 2, 3), Number([3, 7], 2, 2),
                  Number([2, 4], 2, 2), Number([1, 7], 9, 2), 
                  Number([1, 3], 2, 2)]

print sorted(number_objects, key=attrgetter('sets', 'count'))

produces:

[([1, 3], 2, 2), ([1, 3, 7], 2, 3), ([1, 7], 9, 2), ([2, 4], 2, 2), ([3, 7], 2,
2)]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜