Python重命名重复项

标签 python list duplicates rename

如何解决这个重命名重复问题而不诉诸于像 "_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/

相关文章:

python - 从 Python 2 升级到 Python 3 Google App Engine

python - 如何使用 scrapy-redis 管道?

c - 我怎样才能只计算列表中的某些项目?

python - 嵌套列表列表到单个元组列表

python - 用 BeautifulSoup 和多个段落进行抓取

python列表列表索引

java - Proguard 和 lambda 表达式

arrays - 有没有一种简单的方法可以从数组中删除重复的元素?

mysql - cakephp防止重复

python - 具有相同区域设置的不同 datetime.strftime 输出