Ordered intersection of two lists in Python

前端 未结 2 1388
闹比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条回答
  •  Happy的楠姐
    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]
    

提交回复
热议问题