1

I have a list:

ids = ["a", "b", "c", "a", "a", "d", "c"]

I need to create a function which will count duplicates in this list and mark them so that i get this list as a result:

['a', 'b', 'c', 'a_1', 'a_2', 'd', 'c_1']

How to do that? I tried to use list.count method but it doesnt help in this case:

b=[]
for i in ids:
     b.append(i+str(ids.count(i)))

because i get this as a result:

['a3', 'b1', 'c2', 'a3', 'a3', 'd1', 'c2']
avgjoe567
  • 33
  • 3
  • Which language what have you tried so far? – MrTux Nov 10 '20 at 20:30
  • I used Python 3.0(and i have to use it because thats the task) – avgjoe567 Nov 10 '20 at 20:38
  • `ids.count(i)` will return `3` *every* time that `i` is equal to `'a'`, because there are three `'a'`s in the input. If you want to know how many times it has occurred previously in the loop, you will have to keep track of that yourself. – Karl Knechtel Nov 10 '20 at 20:44

1 Answers1

4

You can use a dictionary where the key is an item from your id list and the value is the count. Then when you find a new id, append the id to the output list. However, if the id is already in the dictionary, then increment the count and append the id along with that count to the output list. Finally, return the list. Here is an example code in python:

ids = ["a", "b", "c", "a", "a", "d", "c"]
output_ids = []
id_count = {}

# iterate through ids
for item in ids:
    # if it's a new id
    if item not in id_count:
        # add it to dictionary
        id_count[item] = 0
        # add it to the output as is
        output_ids.append(item)
    # if it's not new
    else:
        # increment its count
        id_count[item] += 1
        # add it to the output along with its count
        output_ids.append(f"{item}_{id_count[item]}")

print(output_ids)  # ['a', 'b', 'c', 'a_1', 'a_2', 'd', 'c_1']
Eyosyas
  • 66
  • 1
  • 5
  • 2
    Note that ['id' is a bad variable name in Python](https://stackoverflow.com/q/77552/4518341) since it's also the name of a builtin. – wjandrea Nov 10 '20 at 21:39
  • Is it a good idea to provide a full solution to someone who has to solve a task (e.g., for university)? – MrTux Nov 12 '20 at 10:24