Python 如何在列表中查找最频繁的元素,但在绘制的情况下,返回具有最后一个索引的元素
类似的问题也被贴出来了,但我不知道如何返回最后一个索引。 我试图解决问题的部分是函数pop()中的b=max(…)Python 如何在列表中查找最频繁的元素,但在绘制的情况下,返回具有最后一个索引的元素,python,arrays,arr,Python,Arrays,Arr,类似的问题也被贴出来了,但我不知道如何返回最后一个索引。 我试图解决问题的部分是函数pop()中的b=max(…) 您能否添加一个示例,其中包含对push和pop的多个调用,以说明某些困难情况下的预期输出?但这没有成功。。。 import itertools import operator class FreqStack: def __init__(self): self.STACK = [] self.output = [] def push(
您能否添加一个示例,其中包含对
push
和pop
的多个调用,以说明某些困难情况下的预期输出?但这没有成功。。。
import itertools
import operator
class FreqStack:
def __init__(self):
self.STACK = []
self.output = []
def push(self, val: int) -> None:
self.STACK.append(val)
def pop(self) -> int:
SL = sorted((x, i) for i, x in enumerate(self.STACK))
groups = itertools.groupby(SL, key=operator.itemgetter(0))
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(self.STACK)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
return count, -min_index
# pick the highest-count/earliest item
b = max(groups, key=_auxfun)[0]
self.STACK.reverse()
try:
self.STACK.remove(b)
except:
pass
self.STACK.reverse()
return b