Python merge lists by common element

前端 未结 6 1510
梦毁少年i
梦毁少年i 2021-01-26 09:24

Im trying to merge two lists that have a common thing between them (in that case is a the id parameter). I have something like this:

list1=[(id1,host1

6条回答
  •  [愿得一人]
    2021-01-26 09:56

    You'll want to go through each of the two lists of lists and add their contents to a new defaultdict with elements of type list.

    This will have the effect of creating a dictionary with contents like {id1: (host1, host5), id2: host2, ...}.

    You can then go through and map the id values to their corresponding IP values.

    Note that in order for this to work, the id values have to be hashable. Strings, numbers, and other basic types are hashable.

    If the id values are objects of a class you've defined, you can have that class inherit from the collections.Hashable abstract base class.

提交回复
热议问题