我有一个清单:
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']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句