按实例属性值对字典排序

2024-10-02 22:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个用python2.6.6编写的程序。它使用的字典如下所示:

{ 'somekeystring': someobject("a name", 1, 3),
'anotherkey': someobject("another name", 2, 2),
'keythree': someobject("third name", 3, 1) }

对象具有以下属性:

name
startOrder
stopOrder

我要做的是把字典整理好。一次someobject.startOrder,一次someobject.stopOrder命令. 你知道吗

我试过了

sortedByStartOrder = sorted(mydict.iteritems(), key=lambda x: x[1].startOrder)

但这似乎不起作用。无论在上面的示例中使用startOrder还是stopOrder,列表项都按相同的顺序排序。你知道吗

有什么提示吗?你知道吗


Tags: 对象name命令程序字典属性another整理
3条回答

这个例子似乎对我有用:

class P:
    def __init__(self, x):
        self.x = x

d = { 'how': P(3), 'hi': P(2), 'you': P(5), 'are': P(4) }
print list(d.iteritems())
print sorted(d.iteritems(), key=lambda x: x[1].x)

产生

>> [('how', <__main__.P instance at 0x7f92028e52d8>), ('you', <__main__.P instance at 0x7f92028e5368>), ('hi', <__main__.P instance at 0x7f92028e5320>), ('are', <__main__.P instance at 0x7f92028e53b0>)]
>> [('hi', <__main__.P instance at 0x7fc210e6c320>), ('how', <__main__.P instance at 0x7fc210e6c2d8>), ('are', <__main__.P instance at 0x7fc210e6c3b0>), ('you', <__main__.P instance at 0x7fc210e6c368>)]

我猜问题不在排序本身;您尝试排序的结构可能有问题。你知道吗

非常感谢您的投入!我写了一个简单的例子,像Odexios的,它与

sortedByStartOrder = sorted(mydict.iteritems(), key=lambda x: x[1].startOrder)

线索是:

I'd guess the problem isn't in the sort itself; there might be something wrong in the structures you're trying to sort.

我浏览了我的代码,找到了一个代码段,我把两个变量都设置为0。你知道吗

您可以定义your own comparing function,它被赋予关键字cmp中的sorted内置项。你知道吗

def sort_by_start(obj1, obj2):
    # this is just an example using '>' and '<' as comparison operators
    # you can compare 1 and 2 using whatever methods you wish; just
    # return a negative number if 1 is less than 2, 0 if they are equal
    # or a positive number if 1 is greater than 2.
    if obj1.startOrder < obj2.startOrder:
        return -1
    if obj1.startOrder > obj2.startOrder:
        return 1
    else:
        return 0

sorted(mydict.iteritems(), cmp=sort_by_start, key=lambda x: x[1])

def sort_by_stop(obj1, obj2):
    # let's make this more specific: imagine `stopOrder` is a string,
    # but we need to remove a prefix before we sort them alphabetically
    common_prefix = 'id-'  # or whatever
    comp1 = obj1.stopOrder.lstrip(common_prefix)
    comp2 = obj2.stopOrder.lstrip(common_prefix)
    if comp1 < comp2:
        return -1
    if comp1 > comp2:
        return 1
    else:
        return 0

sorted(mydict.iteritems(), cmp=sort_by_stop, key=lambda x: x[1])

相关问题 更多 >