对UUID v1列表进行排序的最佳和最快方法是什么:
ss = [(uuid1(), i, time.sleep(i)) for i in range(10)]
ss
[(UUID('9a5e8b20-be62-11e3-87fa-0800270bf8cf'), 0, None), (UUID('9a5e9246-be62-11e3-87fa-0800270bf8cf'), 1, None), (UUID('9af75166-be62-11e3-87fa-0800270bf8cf'), 2, None), (UUID('9c28d4ba-be62-11e3-87fa-0800270bf8cf'), 3, None), (UUID('9df31a58-be62-11e3-87fa-0800270bf8cf'), 4, None), (UUID('a056198a-be62-11e3-87fa-0800270bf8cf'), 5, None), (UUID('a351c986-be62-11e3-87fa-0800270bf8cf'), 6, None), (UUID('a6e63dc0-be62-11e3-87fa-0800270bf8cf'), 7, None), (UUID('4f418380-cfac-11e3-87fa-0800270bf8cf'), 8, None), (UUID('7de51c1e-d075-11e3-87fa-0800270bf8cf'), 9, None)]
使用以下语句并不总是给出正确的结果:
sorted(ss, key= lambda x: x[0])
[(UUID('4f418380-cfac-11e3-87fa-0800270bf8cf'), 8, None), (UUID('7de51c1e-d075-11e3-87fa-0800270bf8cf'), 9, None), (UUID('9a5e8b20-be62-11e3-87fa-0800270bf8cf'), 0, None), (UUID('9a5e9246-be62-11e3-87fa-0800270bf8cf'), 1, None), (UUID('9af75166-be62-11e3-87fa-0800270bf8cf'), 2, None), (UUID('9c28d4ba-be62-11e3-87fa-0800270bf8cf'), 3, None), (UUID('9df31a58-be62-11e3-87fa-0800270bf8cf'), 4, None), (UUID('a056198a-be62-11e3-87fa-0800270bf8cf'), 5, None), (UUID('a351c986-be62-11e3-87fa-0800270bf8cf'), 6, None), (UUID('a6e63dc0-be62-11e3-87fa-0800270bf8cf'), 7, None)]
预期订单为:0,1,2,3,4,5,6,7,8,9而非8,9,0,1,2,3,4,5,6,7
请注意,我要排序的列表只有UUID:在上面的示例中按x [1]排序对我来说不起作用。
答案 0 :(得分:1)
Python的UUID根据int
属性进行排序,该属性是UUID对象的唯一成员。
def __cmp__(self, other):
if isinstance(other, UUID):
return cmp(self.int, other.int)
return NotImplemented
这与UUID v1对象的“timestamp”部分(您可以作为time
属性访问)不同,因为它们引用了具有不同顺序的基础字节序列:
>>> x = uuid.uuid1()
>>> x
UUID('488085a8-be83-11e3-a999-1803733f0b7d')
>>> x.int
96371740624175594482388131032705469309L
>>> ((((((((((x.time_low << 16) | x.time_mid) << 16) | x.time_hi_version) << 8) | x.clock_seq_hi_variant) << 8) | x.clock_seq_low) << 48) | x.node) == x.int
True
>>> x.time
136161884817622440L
>>> (((((x.time_hi_version & 0xFFF) << 16) | x.time_mid) << 32) | x.time_low) == x.time
True
因此,当您根据其时间戳对UUID v1对象进行排序时,需要指定“time”属性:
sorted(ss, key= lambda x: x[0].time)