如何解决这个重命名重复问题而不诉诸于像 "_DUPLICATED_#NO"
这样的独特重命名 完成后名称必须是唯一的,最好用迭代数字表示重复次数
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']
如你所见,名称不是唯一的
最佳答案
这看起来很简单。您从文件名列表开始:
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
将为您提供文件名。
关于Python重命名重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372580/