在多层结构中使用Python组合

2024-10-04 09:28:31 发布

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

我有一本字典,imageHasheskeys=pathsvalues = integers,例如

imageHashes['/directorya/jim.txt'] = 7
imageHashes['/directorya/nigel.txt'] = 68
imageHashes['/directoryb/ralph.txt'] = 17
imageHashes['/directoryb/baba.txt'] = 43

使用组合,我可以循环使用:

for keypair in list(combinations(imageHashes,2)):
    do something

问题是我只想在不同目录的对之间做一些事情,所以

  • jimralph
  • nigelralph
  • jimbaba
  • nigelbaba



  • jimnigel
  • ralphbaba

    我有点神经兮兮的,有人能告诉我最好的开始方式吗

Tags: integerstxtfor字典keysvaluespathsjim
2条回答

如果您想要一种通用方法,即拥有任意数量的目录:

from itertools import product

# get the set of different directories
dirs = {path.rsplit('/', 1)[0] for path in imageHashes}
# get iterators for every directory
dirs_iter = [[path for path in imageHashes if path.startswith(dir)] for dir in dirs]
# and now every possible combination between them
for comb in product(*dirs_iter):
    do something

现在comb将拥有与可用路径中不同目录一样多的元素;也就是说,每个comb都有一个目录路径

无需过度思考:只需使用continue遍历组合并跳过您不想处理的组合。你需要知道的另一件事是如何检查两个文件是否在同一个目录中换句话说,它们的目录名是否匹配?这就是os.path.dirname给我们的

from itertools import combinations
from os.path import dirname

imageHashes = {}
imageHashes['/directorya/jim.txt'] = 7
imageHashes['/directorya/nigel.txt'] = 68
imageHashes['/directoryb/ralph.txt'] = 17
imageHashes['/directoryb/baba.txt'] = 43


for path_a, path_b in combinations(imageHashes, 2):
    if dirname(path_a) == dirname(path_b):
        continue

    print("They're different!: {} vs. {}".format(path_a, path_b))

它给出:

They're different!: /directoryb/baba.txt vs. /directorya/jim.txt
They're different!: /directoryb/baba.txt vs. /directorya/nigel.txt
They're different!: /directorya/jim.txt vs. /directoryb/ralph.txt
They're different!: /directorya/nigel.txt vs. /directoryb/ralph.txt

注意,不需要将combinations返回的迭代器转换为列表:这只是浪费时间

相关问题 更多 >