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

前端 未结 4 2123
旧时难觅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.

    0 讨论(0)
  • 2021-01-22 15:23

    i have tried the following peice of code and it works (changing in one DataStructure changes for the other). does this help?

    list1 = [1,2,3]
    list2 = [4,5,6]
    
    my_dictionary = {}
    my_dictionary["a"] = list1
    my_dictionary["b"] = list2
    
    del list1[0]
    print list1
    print list2
    print my_dictionary
    
    0 讨论(0)
  • 2021-01-22 15:31

    Simply put, there is no way to easily link your two structures.

    You could manipulate the object you point to so that it has some "deleted" state and would act as if it's deleted (while being in both containers).

    However, if all you wanted was a list from a dict, use list(the_dict.values()).

    You could make a class to achieve this, if all else fails. See https://docs.python.org/2/reference/datamodel.html#emulating-container-types for the details on what your class would have to have. Within the class, you would have your "duplicated effort," but if it's correctly implemented it wouldn't be error prone.

    0 讨论(0)
  • 2021-01-22 15:32

    You can always do things like this:

    Pointers in Python?

    (a quick stackoverflow search shows some results)

    But that is messing with more than just data structures. Remember that Python manages memory for you (in most of the cases, pretty well), so you don't have to worry of cleaning after yourself.

    0 讨论(0)
提交回复
热议问题