Is there a 'multimap' implementation in Python?

后端 未结 8 1636
离开以前
离开以前 2020-12-01 01:26

I am new to Python, and I am familiar with implementations of Multimaps in other languages. Does Python have such a data structure built-in, or available in a commonly-used

8条回答
  •  不知归路
    2020-12-01 01:47

    You can take list of tuples and than can sort them as if it was a multimap.

    listAsMultimap=[]
    

    Let's append some elements (tuples):

    listAsMultimap.append((1,'a'))
    listAsMultimap.append((2,'c'))
    listAsMultimap.append((3,'d'))
    listAsMultimap.append((2,'b'))
    listAsMultimap.append((5,'e'))
    listAsMultimap.append((4,'d'))
    

    Now sort it.

    listAsMultimap=sorted(listAsMultimap)
    

    After printing it you will get:

    [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (4, 'd'), (5, 'e')]
    

    That means it is working as a Multimap!

    Please note that like multimap here values are also sorted in ascending order if the keys are the same (for key=2, 'b' comes before 'c' although we didn't append them in this order.)

    If you want to get them in descending order just change the sorted() function like this:

    listAsMultimap=sorted(listAsMultimap,reverse=True)
    

    And after you will get output like this:

    [(5, 'e'), (4, 'd'), (3, 'd'), (2, 'c'), (2, 'b'), (1, 'a')]
    

    Similarly here values are in descending order if the keys are the same.

提交回复
热议问题