Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto increment duplicate values by a specific number in Python?

I am expecting the list to be sorted and then duplicates will be spaced by increments of 0.1. Why is my code below not working? Here is what I am expecting to get versus what my program is returning:

Expected Output: [11, 15, 15.1, 20, 20.1, 20.2, 20.3, 20.4, 30, 30.1, 40, 40.1, 50, 50.1]

Actual output:[11, 15, 15.1, 20, 20.1, 20.1, 20.1, 20.1, 30, 30.1, 40, 40.1, 50, 50.1]

Python Code:

my_list = [20,20,20,30,20,30,40,50,15,11,20,40,50,15]
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:
        my_list[i] = my_list[i] + 0.10

    dup_list.append(my_list[i])
like image 730
Parth Bhodia Avatar asked Dec 31 '25 01:12

Parth Bhodia


1 Answers

You could use itertools.groupby to group equal consecutive elements:

from itertools import groupby

my_list = [20,20,20,30,20,30,40,50,15,11,20,40,50,15]
my_list.sort()
result = [g + i * 0.1 for k, group in groupby(my_list) for i, g in enumerate(group)]
print(result)

Output

[11.0, 15.0, 15.1, 20.0, 20.1, 20.2, 20.3, 20.4, 30.0, 30.1, 40.0, 40.1, 50.0, 50.1]
like image 191
Dani Mesejo Avatar answered Jan 01 '26 16:01

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!