S Person D Person
S Person D Person

Reputation: 331

How to find a duplicate in a list and perform different calculation for each instance of duplicate found?

a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]

I would like to iterate over a_list and find duplicates. If a duplicate is found I would like to perform a calculation on that duplicate. If another duplicate of the same instance is found, a different calculation should be performed.

For example:

Start iterating a_list:

1, 2, 3, 1 [Instance of duplicate 1 found - Perform 1+1 on instance]

Continue iterating...

1, 2, 3, 1, 2 [Instance of duplicate 2 found - Perform 2+2 on instance]

Continue iterating...

1, 2, 3, 1, 2, 3 [Instance of duplicate 3 found - Perform 3+3 on instance]

Continue iterating...

1, 2, 3, 1, 2, 3, 1 [Second instance of duplicate 1 found - Perform 1+1+1 on instance]

Continue iterating...

1, 2, 3, 1, 2, 3, 1, 2 [Second instance of duplicate 2 found - Perform 2+2+2 on instance]

Continue iterating...

1, 2, 3, 1, 2, 3, 1, 2, 3 [Second instance of duplicate 3 found - Perform 3+3+3 on instance]

Once completed a new list is created with all calculations included:

new_list = [1, 2, 3, 2, 4, 6, 3, 6, 9]

Could someone explain to me how to find duplicates as well as count the instances of these duplicates, so that I can perform a different calculation on each new instance of the duplicate?

Upvotes: 1

Views: 62

Answers (2)

AMC
AMC

Reputation: 2702

This is a tweaked version of the answer by @Alexander, for the fans collections.defauldict out there.

import collections as colls

a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
d = colls.defaultdict(int)
result = []

for val in a_list:
    d[val] += val
    result.append(d[val])

print(result)

Output:

[1, 2, 3, 2, 4, 6, 3, 6, 9]

Upvotes: 1

Parakiwi
Parakiwi

Reputation: 611

I would use a dictionary to keep track of what values have been used, and the number of times.

a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
tracking_dict = {}
out_list = []
for item in a_list:
    # checks if item has been seen before
    if item in tracking_dict:
        # add the number as many times as it has been seen
        out_list.append(item + item * tracking_dict[item])
        # since you've seen the number, increase the count by 1
        tracking_dict[item] += 1
    else:
        # add it to the output list as-is
        out_list.append(item)
        # the item is new to this list
        tracking_dict[item] = 1
print(out_list)

Hope this helps!

Upvotes: 1

Related Questions