python - In Python3, how to create a priority queue based on the second element of its sublist -
for example, have list sublists:
a = [[1,83],[2,7],[3,10]] i want create priority queue based on second element of a's sublist,which means if use
a.pop() the output
[2,7] since has smallest second element.
subclassing built-in list:
>>> class mylist(list): ... def pop(self, index=none): ... if index none: ... try: ... index = min(enumerate(self), key=lambda x: x[1][1])[0] ... except valueerror: ... # allow empty lists ... pass ... args = () if index none else (index,) ... return super(mylist, self).pop(*args) ... ... >>> l = mylist([[1,83],[2,7],[3,10]]) >>> l.pop() [2, 7] >>> l [[1, 83], [3, 10]] hack way works on directly on built-in list instead of custom class:
>>> import gc >>> >>> def mypop(list_, index=none): ... if index none: ... try: ... index = min(enumerate(list_), key=lambda x: x[1][1])[0] ... except valueerror: ... # allow empty lists ... pass ... args = () if index none else (index,) ... return list_.pop(*args) ... >>> gc.get_referents(list.__dict__)[0]["mypop"] = mypop >>> >>> l = [[1,83],[2,7],[3,10]] >>> l.mypop() [2, 7] >>> l.mypop() [3, 10] >>> l.mypop() [1, 83] >>> l.mypop() traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 9, in mypop indexerror: pop empty list ^ hey, don't use this, post here fun!
Comments
Post a Comment