Home > Back-end >  How to auto increment duplicate values by sequence of repetitions
How to auto increment duplicate values by sequence of repetitions

Time:02-08

I'm trying to add an indication of the number of sequence of repetitions of integers in my_list:

my_list = [20,20,20,30,20,30,40,50,15,11,
           20,40,50,15,20,20,20,50,50]
#my_list.sort()
dup_list = []


for i in range (len(my_list)):
    if my_list[i] not in dup_list:
        dup_list.append(my_list[i])
    else:
        j=1
        res = True
        while res:
            val = my_list[i] j*0.1
            if val  not in dup_list:
                dup_list.append(val)
                res = False
            j =1 

print(dup_list)

the result that I obtain

[20, 20.1, 20.2, 30, 20.3, 30.1, 40, 50, 15, 11, 20.4, 40.1, 50.1, 
 15.1, 20.5, 20.6, 20.7, 50.2, 50.3]

The result that I Look for:

[20.0, 20.0, 20.0, 30.0, 20.1, 30.1, 40.0, 50.0, 15.0, 11.0, 20.2, 
 40.1, 50.1, 15.1, 20.3, 20.3, 20.3, 50.2, 50.2]

CodePudding user response:

As mentioned in the comments, floating point arithmetic is prone to precision issues.Anyway, you can keep track of the current value of every unique item by using a dictionary:

x = [20, 20, 20, 30, 20, 30, 40, 50, 15, 11, 20, 40, 50, 15, 20, 20, 20, 50, 50]
current_values = dict(zip(x, x))

new_x = []
last_seen = x[0]
for item in x:
     if item != last_seen:
         current_values[last_seen] = round(current_values[last_seen]   0.1, 2)
         last_seen = item
     new_x.append(current_values[item])

Result:

In [3]: new_x == desired
Out[3]: True

Note that since you haven't specified yet what you'd want to do in the case there is more than 10 duplicates, right now you'd start getting 21.0, etc. This should be enough to help you solve your problem and give you something to modify if you need.

CodePudding user response:

You could use a dictionary dup that you use to keep track of the duplicate values as you iterate over my_list. Update dup whenever a new number is encountered or if a number that is a duplicate but different from the number preceding it:

out = [my_list[0]]
dup = {out[0]: 0}
for i,j in zip(my_list, my_list[1:]):
    if j in dup:
        if i!=j:
            dup[j]  = 0.1
    else:
        dup[j] = 0
    out.append(j dup[j])

Output:

out = [20.0, 20.0, 20.0, 30.0, 20.1, 30.1, 40.0, 50.0, 15.0, 11.0, 20.2, 40.1, 50.1, 15.1, 20.3, 20.3, 20.3, 50.2, 50.2]
  •  Tags:  
  • Related