简体   繁体   English

如何索引列表中的重复项?

[英]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:我尝试使用 list.count 方法,但在这种情况下没有帮助:

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.您可以使用字典,其中键是 id 列表中的一个项目,值是计数。 Then when you find a new id, append the id to the output list.然后当你找到一个新的 id 时,将该 id 附加到输出列表中。 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.但是,如果 id 已经在字典中,则增加计数并将 id 与该计数一起附加到输出列表中。 Finally, return the list.最后,返回列表。 Here is an example code in python:这是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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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