Ordered intersection of two lists in Python

前端 未结 2 1386
闹比i
闹比i 2020-12-10 12:12

I know that in Python, if I have:

list_1 = [1,2,3]
list_2 = [2,3,4]

I can do the following to find the intersection between the two:

<
相关标签:
2条回答
  • 2020-12-10 12:46

    Use the index-method of lists as sort criterion:

    l1 = [3, 2, 1]
    l2 = [2, 3, 4]
    sorted(set(l1) & set(l2), key = l1.index)
    

    Out:

    [3, 2]
    
    0 讨论(0)
  • 2020-12-10 13:03
    set_2 = frozenset(list_2)
    intersection = [x for x in list_1 if x in set_2]
    

    set instead of frozenset works too, I'm just increasingly in the habit of using immutable classes in cases where I don't intend to mutate the data. The point is that to maintain order you need to traverse the list in the order you want to maintain, but you don't want to have the n*m complexity of the naive approach: [x for x in list_1 if x in list_2]. Checking for membership in a set or similar hash-based type is roughly O(1), compared to O(n) for membership in a list.

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