python中同一项中的计数器出现次数

python中同一项中的计数器出现次数,python,group-by,counter,Python,Group By,Counter,对不起,我很确定其他人可能已经问过这个问题了,但我没有找到。我想记录下我看到这个特定项目的次数,比如 输入: [88,88,27,0,88] 期望输出: [1,2,1,1,3] 我在寻找性能特别好的东西。 我同意Numpy或Pandas解决方案 >>> from collections import defaultdict ... ... ... def solution(lst): ... result = [] ... seen = defaultd

对不起,我很确定其他人可能已经问过这个问题了,但我没有找到。我想记录下我看到这个特定项目的次数,比如

输入:

[88,88,27,0,88]
期望输出:

[1,2,1,1,3]
我在寻找性能特别好的东西。 我同意Numpy或Pandas解决方案

>>> from collections import defaultdict
... 
... 
... def solution(lst):
...     result = []
...     seen = defaultdict(int)
...     for num in lst:
...         seen[num] += 1
...         result.append(seen[num])
...     return result
... 
>>> solution([88, 88, 27, 0, 88])
[1, 2, 1, 1, 3]
>>> solution([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])
[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]
没有进口:

>>> def solution(lst):
...     result = []
...     seen = {}
...     for num in lst:
...         try:
...             seen[num] += 1
...         except KeyError:
...             seen[num] = 1
...         result.append(seen[num])
...     return result
... 
>>> solution([88, 88, 27, 0, 88])
[1, 2, 1, 1, 3]
>>> solution([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])
[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]

下面是使用列表理解的简单方法:

x = [8,1,2,3,1,3,3,1,2,99]
y = [x[:i].count(el) + 1 for i, el in enumerate(x)]
print(y)
输出:

[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]
带发电机的输出:

def return_count(l):
    cnt = {}
    for x in l:
        cnt[x] = cnt.get(x, 0) + 1
        yield cnt[x]

print(list(return_count([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])))

为什么这是你想要的输出?检查。想要的输出的第一项意味着这是我第一次看到“8”,这可以在一次通过中解决,没有切片,没有重复计数。Thk是你的答案,但这似乎非常昂贵我同意你的看法,实际上,这取决于你的答案的输入大小。Thks,但我不希望为你的答案导入此集合libraryThks。你知道Numpy有什么实现吗?
def return_count(l):
    cnt = {}
    for x in l:
        cnt[x] = cnt.get(x, 0) + 1
        yield cnt[x]

print(list(return_count([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])))