簡體   English   中英

如何索引列表中的重復項?

[英]how to index duplicates in a list?

我有一個清單:

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

我需要創建一個函數來計算這個列表中的重復項並標記它們,以便我得到這個列表:

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

怎么做? 我嘗試使用 list.count 方法,但在這種情況下沒有幫助:

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

因為我得到了這個結果:

['a3', 'b1', 'c2', 'a3', 'a3', 'd1', 'c2']

您可以使用字典,其中鍵是 id 列表中的一個項目,值是計數。 然后當你找到一個新的 id 時,將該 id 附加到輸出列表中。 但是,如果 id 已經在字典中,則增加計數並將 id 與該計數一起附加到輸出列表中。 最后,返回列表。 這是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