Manko
Manko

Reputation: 91

python edit tuple duplicates in a list

my target is: while for looping a list I would like to check for duplicates and if there are some i would like to append a number to it see following example

my list output as an example:

[('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]

in a loop i would like to edit those duplicates so instead of the 2nd microsoft i would like to have microsoft1 (if there would be 3 microsoft guys so the third guy would have microsoft2)

with this i can filter the duplicates but i dont know how to edit them directly in the list

    list = [('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]

        names = []
        double = []
        for u in list[1:]:
            names.append(u[1])
            list_size = len(names)
            for i in range(list_size):
                k = i + 1
                for j in range(k, list_size):
                    if names[i] == names[j] and names[i] not in double:
                        double.append(names[i])

Upvotes: 0

Views: 56

Answers (1)

Rakesh
Rakesh

Reputation: 82765

This is one approach using collections.defaultdict.

Ex:

from collections import defaultdict
lst = [('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]
seen = defaultdict(int)
result = []
for k, v in lst:
    if seen[v]:
        result.append((k, "{}_{}".format(v, seen[v])))
    else:
        result.append((k,v))
    seen[v] += 1

print(result)

Output:

[('name', 'company'),
 ('someguy', 'microsoft'),
 ('anotherguy', 'microsoft_1'),
 ('thirdguy', 'amazon')]

Upvotes: 3

Related Questions