0

タプルを使用して別の Dictionary 内のリストの順列を見つけようとしています。

たとえば、次の[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)

4

1 に答える 1

2

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
于 2013-07-06T23:01:37.473 に答える