I have these indexes: [3,1,1,2] And I need to append these items:
[Item("beer", 4), Item("steak", 1), Item("hamburger", 1), Item("donut", 3)]
to list, to be like in this particular order
[ Item("hamburger", 1),Item("steak", 1), Item("donut", 3),Item("beer", 4)]
Im doing it in python, i tried it many ways but none of it worked properly
CodePudding user response:
The following builds a priority queue, where the "indices" indicate the priority of each item:
>>> indices = [3, 1, 1, 2]
>>> items = [("beer", 4), ("steak", 1), ("hamburger", 1), ("donut", 3)]
>>> from bisect import bisect_left
>>> prio = []
>>> new = []
>>> for i, item in zip(indices, items):
... index = bisect_left(prio, i)
... prio.insert(index, i)
... new.insert(index, item)
...
>>> new
[('hamburger', 1), ('steak', 1), ('donut', 3), ('beer', 4)]