2017-09-22 90 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检查我的编辑,如果你使用它来创建文件。 –