A list as a key for a dictionary

前端 未结 5 1911
一整个雨季
一整个雨季 2021-01-22 08:28

I have multiple lists of tuples eg

[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]

that I would like to have as keys to a dictionary (so each key in my dic

5条回答
  •  时光取名叫无心
    2021-01-22 08:37

    >>> def nested_lists_to_tuples(ls):
        return tuple(nested_lists_to_tuples(l) if isinstance(l, (list, tuple)) else l for l in ls)
    
    >>> nested_lists_to_tuples([([1,2,3,4],2),([5,6,7],3)])
    (((1, 2, 3, 4), 2), ((5, 6, 7), 3))
    

    Then just use that returned value as your key. Note that I did it this way so you could support even more deeply nested mixes of tuples and lists, like [([1,(2, [3, 4, [5, 6, (7, 8)]]), 3, 4], 2), ([5, 6, 7], 3)]:

    >>> nested_lists_to_tuples([([1, (2, [3, 4, [5, 6, (7, 8)]]), 3, 4], 2), ([5, 6, 7], 3)])
    (((1, (2, (3, 4, (5, 6, (7, 8)))), 3, 4), 2), ((5, 6, 7), 3))
    

    There may possibly be a simpler way to do this, though.

提交回复
热议问题