下面是一個包含重複的列表:如何追加計數數字在Python中的列表中重複?
l1 = ['a', 'b', 'c', 'a', 'a', 'b']
這裏是理想的結果:
l1 = ['a', 'b', 'c', 'a_1', 'a_2', 'b_1']
如何能重複通過附加一個計數改名?
這是試圖達到這個目標;然而,是否有更多的Pythonic方式?
for index in range(len(l1)):
counter = 1
list_of_duplicates_for_item = [dup_index for dup_index, item in enumerate(l1) if item == l1[index] and l1.count(l1[index]) > 1]
for dup_index in list_of_duplicates_for_item[1:]:
l1[dup_index] = l1[dup_index] + '_' + str(counter)
counter = counter + 1
我想你想'a_1'而不是'a'_1? – exupero 2010-05-14 21:36:22
對不起,其'a_1'=) – myeu2 2010-05-14 22:13:20