【问题标题】:How to find combinations of a list in a Dictionary?如何在字典中查找列表的组合?
【发布时间】:2013-07-06 22:59:16
【问题描述】:

我正在尝试在另一个带有元组的字典中查找列表的任何排列。

例如,在字典中查找[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) )。

【问题讨论】:

    标签: python dictionary tuples permutation


    【解决方案1】:

    使用itertools.permutations() 生成列表的所有排列:

    from itertools import permutations
    
    if any(tuple(perm) in yourdictionary for perm in permutations(yourlist)):
        # match found
    

    但您确实想重新考虑您的数据结构。如果您将密钥设为 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
    

    【讨论】:

    • 是的,既然您指出了这一点。我不只是将格式更改为有组织的格式,这似乎很荒谬。非常感谢。
    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2017-09-20
    • 2021-12-14
    • 1970-01-01
    • 2010-12-02
    • 2018-01-11
    相关资源
    最近更新 更多