抱歉,我相信可能已经有其他人问过这个问题了,但我没有找到。我想追踪我看到这个特定项目的次数,例如:
输入:
输入:
[88,88,27,0,88]
期望的输出:
[1,2,1,1,3]
我正在寻找在性能方面尤为出色的解决方案。Numpy或Pandas的解决方案都可以。
以下是使用列表推导式的简单方法:
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]
lst = [8,1,2,3,1,3,3,1,2,99]
cnt = {}
res = []
for x in lst:
cnt[x] = cnt.get(x,0)+1
res += [cnt[x]]
print(res)
输出
>>> 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]
使用生成器的一个例子:
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])))