简体   繁体   中英

Sort a list of objects according to a property in another list

My data consists of objects with some property ( pk ):

obj0.pk = 'aa'
obj1.pk = 33
ojb2.pk = 'm0'

I have a bunch of unordered objects:

data = [obj0, obj1, obj2]

And I have the list of pks which specify how to order the objects:

pks = [33, 'aa', 'm0']

Now I call a function to order the data:

output = sort_data_by_pk(data, pks)

Expected output:

[obj1, obj0, obj2]

How can we implement sort_data_by_pk in python?

EDIT

My initial implementation is:

def sort_data_by_pk(data, pks):
    lookup = {instance.pk: instance for instance in data}
    return [lookup[pk] for pk in pks]

Using the index method as a key function unnecessarily makes the solution O(n^2 log n) rather than O(n log n) in average time complexity.

Instead, you can build a dict that maps the items in data to their indices, so that you can use the dict to map the objects' pk attribute as a key function for sort order:

order = {k: i for i, k in enumerate(pks)}
output = sorted(data, key=lambda o: order[o.pk])

You could sort data based on the index in the pks like,

>>> pks = [33, 'aa', 'm0']
>>> data = [ob0, ob1, ob2]
>>> 
>>> 
>>> sorted(data, key=lambda x: pks.index(x.pk))
[<__main__.Obj object at 0x7f03851cc290>, <__main__.Obj object at 0x7f03851cc250>, <__main__.Obj object at 0x7f03851cc2d0>]

我认为您想使用带lambda的sorted来获取pks主键的索引。

sorted_data = sorted(data, lambda d: pks.index(d.pk))

If your lists are big, you might want to create a dict first, to avoid multiple calls of "index" on the list.

pks = [33, 'aa', 'm0']
data = [ob0, ob1, ob2]
d = { obj.pk: obj for obj in data } #lookup table for pks
sorted_list = [ d[pk] for pk in pks ] #create a new list out of list "pks" where pk is replaced by the value in the lookup table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM