[英]How to set new values to list, with same numbers occurring multiple times?
I'm trying to set new values based on an existing list with values rather randomly set.我正在尝试根据现有列表设置新值,而值是随机设置的。 Some values appear multiple times and the new index value should reflect that.
有些值出现多次,新的索引值应该反映出来。 However, I seem unable to count a value that appears multiple times as 1, to then add to a counter (
startval
).但是,我似乎无法将多次出现的值计为 1,然后添加到计数器(
startval
)。 What would be a good way of doing this?这样做的好方法是什么?
startval = 901
old_index = [100, 145, 145, 740, 740, 740, 276, 277, 278]
# new_index = [901, 902, 902, 903, 903, 903, 904, 905, 906]
new_index = []
for x in old_index:
new_index.append(startval)
if old_index.count(x) != 1:
for y in range(old_index.count(x)):
startval *=1 #but add 1 once
else:
startval +=1
You can use the old defaultdict
size trick to get contiguous integer keys corresponding to a set of (repeating) values:您可以使用旧的
defaultdict
大小技巧来获取与一组(重复)值对应的连续 integer 键:
from collections import defaultdict
old_index = [100, 145, 145, 740, 740, 740, 276, 277, 278]
offset = 901
index = defaultdict(lambda: len(index) + offset)
new_index = [index[v] for v in old_index]
# [901, 902, 902, 903, 903, 903, 904, 905, 906]
If you only want the same index for neighbouring duplicates, you can go with itertools.groupby
and enumerate
:如果您只想为相邻的重复项使用相同的索引,则可以使用
itertools.groupby
和enumerate
go :
from itertools import groupby
new_index = [i for i, (_, g) in enumerate(groupby(old_index), offset) for _ in g]
# [901, 902, 902, 903, 903, 903, 904, 905, 906]
Some documentation:一些文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.