Python 如何在字典中查找列表的组合?

Python 如何在字典中查找列表的组合?,python,dictionary,tuples,permutation,Python,Dictionary,Tuples,Permutation,我试图在另一本有元组的字典中找到列表的任何排列 例如,在如下格式的词典中查找[1,2,3]的任何组合的最佳方法是什么:{(1,3,2):'text',(3,1,2):'text'} 符合[1,2,3]条件的唯一匹配项是(1,2,3)、(1,3,2)、(2,1,3)、(2,3,1)、(3,2,1)、(3,1,2) 不符合条件的匹配项包括不包含所有项的列表(例如:(1,2)或(2)),以及包含额外项的匹配项(例如:(1,2,3,4)或(2,3,7,1))。用于生成列表的所有排列: from iter

我试图在另一本有元组的字典中找到列表的任何排列

例如,在如下格式的词典中查找
[1,2,3]
的任何组合的最佳方法是什么:
{(1,3,2):'text',(3,1,2):'text'}

符合
[1,2,3]
条件的唯一匹配项是
(1,2,3)、(1,3,2)、(2,1,3)、(2,3,1)、(3,2,1)、(3,1,2)

不符合条件的匹配项包括不包含所有项的列表(例如:
(1,2)
(2)
),以及包含额外项的匹配项(例如:
(1,2,3,4)
(2,3,7,1)
)。

用于生成列表的所有排列:

from itertools import permutations

if any(tuple(perm) in yourdictionary for perm in permutations(yourlist)):
    # match found
但您确实想重新思考您的数据结构。如果您制作了keys
frozenset()
对象,您只需测试:

if frozenset(yourlist) in yourdictionary:
    # match found
这样会快得多

演示:

>>> from itertools import permutations
>>> yourdictionary = {(1,3,2):'text',(3,1,2):'text'}
>>> yourlist = [1, 2, 3]
>>> print any(tuple(perm) in yourdictionary for perm in permutations(yourlist))
True
>>> yourdictionary = {frozenset([1, 2, 3]): 'text', frozenset([4, 5, 6]): 'othertext'}
>>> frozenset(yourlist) in yourdictionary
True
>>> frozenset([2, 3]) in yourdictionary
False

是的,现在你指出了。我不只是把格式改成有条理的,这似乎很不可思议。谢谢。