我有一组文件名来自两个不同的目录。
currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3', etc.])我的代码正在处理这些文件,需要通过将currList与其在前一次迭代中的内容进行比较来更改它,processLst说。为此,我计算了一个对称差分:
toProcess=set(currList).symmetric_difference(set(processList))实际上,我需要symmetric_difference来操作basename (file1.)在完整的文件名(pathA/file1 1)上没有。
我想我需要重新实现__eq__操作符,但是我不知道如何在python中这样做。
__eq__是正确的方法吗?或发布于 2012-10-09 08:53:57
你可以用生成器表达式的魔力来完成这个任务。
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,它们的基名-在两个列表中的存在是不一样的。
编辑:运行此操作时:
currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3'])
processList=set(['pathA/file1', 'pathA/file9', 'pathA/file3'])返回:
set(['pathA/file2', 'pathA/file9'])这似乎是正确的。
发布于 2012-10-09 15:24:48
这里有一个象征性的(也可能构造得很糟糕) 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)))https://stackoverflow.com/questions/12795860
复制相似问题