我想在列表中找到所有userId的开始和结束索引,因为数据集很大,所以我不想指定每个userId就可以这样做。
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1.......213,213,213,213]
我希望输出是
[{1: 0, 20},{2: 21, 40}.....{213: 29,703, 30,000}]
是否有可以在python中自动执行此操作的软件包或函数?
你可以这样做:
from collections import Counter
a = ...
a_counter = Counter(a)
a_indices = []
running_count = 0
for x, x_count in sorted(a_counter.items()):
a_indices.append({x: (running_count, running_count + x_count - 1)})
running_count += x_count
例如,如果a = [1, 1, 2, 2, 3, 3]
,a_indices = [{1: (0, 1)}, {2: (2, 3)}, {3: (4, 5)}]
(最接近你的输出格式,同时为有效)。
如果您愿意稍微更改输出格式,请使用:
a_indices = {}
running_count = 0
for x, x_count in sorted(a_counter.items()):
a_indices[x] = (running_count, running_count + x_count - 1)
running_count += x_count
现在a_indices
,对于a
上述情况,将是{1: (0, 1), 2: (2, 3), 3: (4, 5)}
一个更好用的结构。
这两种解决方案都将使每个结束索引具有x
包容性。如果要使其排他,请替换running_count + x_count - 1
为running_count + x_count
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句