Python: How to create a common element between a list and a dict

前端 未结 4 2124
旧时难觅i
旧时难觅i 2021-01-22 14:57

I am new to data structures in python and was wondering how do you simulate a thing like pointers in python so that multiple structures can refer and manage the same piece of da

4条回答
  •  故里飘歌
    2021-01-22 15:18

    It really depends on the point you're trying to solve by cross-referencing.


    Suppose your intent is to be able to efficiently both locate an item by key, as well as to sequentially iterate by order. In this case, irrespective of the language, you probably would wish to avoid cross referencing a hash-table and an array data structures, as the updates are inherently linear. Conversely, cross referencing a hash-table and a list might make more sense.

    For this, you can use something like llist:

     d = {}
     l = llist.dllist()
    
     # insert 'foo' and obtain the link
     lnk = l.append('foo')
     # insert the link to the dictionary
     d['foo'] = lnk
    

    Conversely, suppose your intent is to be able to efficiently both locate an item by key, as well as to locate by index. Then you can use a dict and a list, and rebuild the list on each modification of the dict. There is no real reason for fancy cross-referencing.

提交回复
热议问题