我目前正在研究用Python 2.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,列表项都按相同的顺序排序。
任何提示?
答案 0 :(得分:1)
这个例子似乎对我有用:
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>)]
我猜这个问题不在排序本身;在您尝试排序的结构中可能存在问题。
答案 1 :(得分:1)
非常感谢您的所有投入!我写了一个像Odexios&#39;这样的简单例子。
与之完美配合sortedByStartOrder = sorted(mydict.iteritems(), key=lambda x: x[1].startOrder)
线索是:
我猜这个问题不在排序本身;可能有 在你尝试排序的结构中出现了问题。
我查看了代码并找到了一个代码段,我将两个变量都设置为0.
答案 2 :(得分:0)
您可以定义sorted
内置于关键字cmp
内置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])
的{{3}}。
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException:
SELECT name, city, state FROM customer
: La tabla/vista 'CUSTOMER' no existe.
root cause
java.sql.SQLSyntaxErrorException: La tabla/vista 'CUSTOMER' no existe.
root cause
org.apache.derby.client.am.SqlException: La tabla/vista 'CUSTOMER' no existe.
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1 logs.