简体   繁体   中英

how to index duplicates in a list?

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']

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM