2017-09-22 91 views
1

如何解決這一更名,而不訴諸具有獨特的像"_DUPLICATED_#NO"名字的東西重命名重複的問題必須在完成時是唯一的,最好用迭代數字表示重複的數量Python的重命名複製

from collections import defaultdict 

l = ["hello1","hello2","hello3", 
    "hello","hello","hello"] 

tally = defaultdict(lambda:-1) 
for i in range(len(l)): 
    e = l[i] 
    tally[e] += 1 
    if tally[e] > 0: 
     e += str(tally[e]) 
    l[i] = e 
print (l) 

結果:

['hello1', 'hello2', 'hello3', 'hello', 'hello1', 'hello2'] 

,你可以看到,該名稱不是唯一的

回答

4

這似乎很簡單。你開始用一個文件名列表:

l = ["hello1","hello2","hello3", 
    "hello","hello","hello"] 

然後你遍歷他們由1如果重複的發現完成的文件名,遞增尾隨數。

result = {} 
for fname in l: 
    orig = fname 
    i=1 
    while fname in result: 
     fname = orig + str(i) 
     i += 1 
    result[fname] = orig 

這應該離開你就像一本字典:

{"hello1": "hello1", 
"hello2": "hello2", 
"hello3": "hello3", 
"hello": "hello", 
"hello4": "hello", 
"hello5": "hello"} 

當然,如果你不關心原件映射到重複的名稱,你可以刪除該部分。

result = set() 
for fname in l: 
    orig = fname 
    i=1 
    while fname in result: 
     fname = orig + str(i) 
     i += 1 
    result.add(fname) 

如果你以後想要一個列表,只需要這樣。

final = list(result) 

請注意,如果你創建的文件,這也正是tempfile模塊是專門做。

import tempfile 

l = ["hello1","hello2","hello3", 
    "hello","hello","hello"] 

fs = [tempfile.NamedTemporaryFile(prefix=fname, delete=False, dir="/some/directory/") for fname in l] 

這不會帶來很好的遞增文件名,但他們保證唯一的,並且fs將是(開放)的文件對象,而不是名稱的列表清單,雖然NamedTemporaryFile.name會給你的文件名。

+2

@PRMoureu固定。哎呀,算法很難;)這將'''hello1','hello1']'變成'['hello1','hello11​​']',但我想不出一個好的方法來概括一個解決方案,產生'['hello1','hello2']'的方式不會破壞其他不太明顯的邊緣情況。 –

+1

這是好的,做得好,沒有想到使用while while _ _ – citizen2077

+1

@new_to_coding檢查我的編輯,如果你使用它來創建文件。 –