从大列表中识别最新版本文件的更好逻辑是什么

What is the better logic for identifying the latest versioned files from a big list

我在一个文件夹中有 200 张图像,每个文件可能包含多个版本(例如:car_image#2、car_image#2、bike_image#2 等)。我的要求是构建一个实用程序,将所有最新文件从该目录复制到另一个目录。

我的做法是:

  1. 将图像名称(不包含版本号)放入列表
  2. 消除列表中的重复项
  3. 遍历列表并确定每个唯一文件的最新版本(我对这一步有点模糊) 有人可以扔一些更好的 ideas/algorithm 来实现这个目标吗?

我的方法是:

  1. 通过获取每个文件名直到 # 来制作唯一名称列表,只添加唯一值。
  2. 创建一个以文件名为键的字典,并将值设置为版本号,当它大于存储的版本号时更新。
  3. 浏览字典并生成要抓取的文件名。

我的首选是 python 脚本,但您应该能够使用您认为合适的几乎任何语言来执行此操作。

获取文件名列表的示例代码:

#get the filename list
myList = []
for x in file_directory:
    fname = x.split("#")[0]
    if not fname in myList:
        myList = myList + [fname]
myDict = {}
for x in myList:
    if not x in myDict:
        myDict[x] = 0
for x in file_directory:
    fversion = x.split("#")[-1]
    if myDict[x] < int(fversion):
        myDict[x] = fversion
flist = []
for x in myDict:
    fname = str(x) + "#" + str(myDict[x])
    flist.append(fname)

然后flist将是最新版本的文件名列表

我没有运行这个或任何东西,但希望它能有所帮助!

在Python3

>>> images = sorted(set(sum([['%s_image#%i' % (nm, random.randint(1,9)) for i in range(random.randint(2,5))] for nm in 'car bike cat dog man tree'.split()], [])))
>>> print('\n'.join(images))
bike_image#2
bike_image#3
bike_image#4
bike_image#5
car_image#2
car_image#7
cat_image#3
dog_image#2
dog_image#5
dog_image#9
man_image#1
man_image#2
man_image#4
man_image#6
man_image#7
tree_image#3
tree_image#4
>>> from collections import defaultdict
>>> image2max = defaultdict(int)
>>> for image in images:
    name, _, version = image.partition('#')
    version = int(version)
    if version > image2max[name]:
        image2max[name] = version


>>> # Max version
>>> for image in sorted(image2max):
    print('%s#%i' % (image, image2max[image]))


bike_image#5
car_image#7
cat_image#3
dog_image#9
man_image#7
tree_image#4
>>>