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
).
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
CodePudding user response:
You can use the old defaultdict
size trick to get contiguous integer keys corresponding to a set of (repeating) values:
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
:
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: