簡體   English   中英

重新實現__eq__以在python中比較集與symmetric_difference

[英]re-implement __eq__ to compare sets with symmetric_difference in python

我有一組來自兩個不同目錄的文件名。

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

我的代碼正在處理文件,需要通過將currList與前一次迭代的內容進行比較來更改currList,比如processLst。 為此,我計算了一個對稱差異:

toProcess=set(currList).symmetric_difference(set(processList))

實際上,我需要symmetric_difference來操作basename(file1 ...)而不是完整的文件名(pathA / file1)。

我想我需要重新實現__eq__運算符,但我不知道如何在python中執行此操作。

  1. 正在重新實現__eq__正確的方法? 要么
  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,並且它們在兩個列表中的basename-presence不同。

編輯:運行此:

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

收益:

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

這似乎是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM