在python中用对称差分比较集的再实现

2024-09-25 00:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组来自两个不同目录的文件名。在

currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3', etc.])

我的代码正在处理这些文件,需要更改currList 通过将它与前一次迭代的内容进行比较,比如processLst。 为此,我计算了一个对称差:

^{pr2}$

实际上,我需要对称的差异来操作basename(file1…)而不是 在完整的文件名(pathA/file1)上。在

我想我需要重新实现__eq__操作符,但我不知道如何在python中实现它。在

  1. 重新实现__eq__是正确的方法吗? 或者
  2. 是否有其他更好/等效的方法?在

Tags: 文件方法代码目录内容文件名etcfile1
2条回答

这里有一个令牌(可能构造不好)itertools版本,如果速度成为一个问题,它应该运行得更快一点(尽管同意@Zarkonnen的一行代码非常好,所以+1在这里:)。在

from itertools import ifilter

currList = set(['pathA/file1', 'pathA/file2', 'pathB/file3'])
processList=set(['pathA/file1', 'pathA/file9', 'pathA/file3'])

# This can also be a lambda inside the map functions - the speed stays the same
def FileName(f):
  return f.split('/')[-1]

# diff will be a set of filenames with no path that will be checked during
# the ifilter process
curr = map(FileName, list(currList))
process = map(FileName, list(processList))
diff = set(curr).symmetric_difference(set(process))

# This filters out any elements from the symmetric difference of the two sets
# where the filename is not in the diff set
results = set(ifilter(lambda x: x.split('/')[-1] in diff,
              currList.symmetric_difference(processList)))

您可以使用生成器表达式的魔力来实现这一点。在

def basename(x):
    return x.split("/")[-1]

result = set(x for x in set(currList).union(set(processList)) if (basename(x) in [basename(y) for y in currList]) != (basename(x) in [basename(y) for y in processList]))

应该会成功的。它提供了出现在一个列表或另一个列表中的所有元素X,并且它们在两个列表中的基名不相同。在

编辑: 运行时使用:

^{pr2}$

退货:

set(['pathA/file2', 'pathA/file9'])

这似乎是正确的。在

相关问题 更多 >