首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重新实现__eq__以比较python中的集合和symmetric_difference

重新实现__eq__以比较python中的集合和symmetric_difference
EN

Stack Overflow用户
提问于 2012-10-09 08:28:31
回答 2查看 197关注 0票数 1

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

代码语言:javascript
复制
currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3', etc.])

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

代码语言:javascript
复制
toProcess=set(currList).symmetric_difference(set(processList))

实际上,我需要symmetric_difference来操作basename (file1.)在完整的文件名(pathA/file1 1)上没有。

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

  1. 重新实现__eq__是正确的方法吗?或
  2. 还有其他更好的/同等的方法吗?
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-09 08:53:57

你可以用生成器表达式的魔力来完成这个任务。

代码语言:javascript
复制
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,它们的基名-在两个列表中的存在是不一样的。

编辑:运行此操作时:

代码语言:javascript
复制
currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3'])
processList=set(['pathA/file1', 'pathA/file9', 'pathA/file3'])

返回:

代码语言:javascript
复制
set(['pathA/file2', 'pathA/file9'])

这似乎是正确的。

票数 1
EN

Stack Overflow用户

发布于 2012-10-09 15:24:48

这里有一个象征性的(也可能构造得很糟糕) itertools版本,如果速度引起关注的话,它应该运行得更快一些(尽管同意@Zarkonnen的一行代码非常贴心,所以+1 :)。

代码语言:javascript
复制
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)))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12795860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档