首页 > 解决方案 > Python中的交叉口保持秩序

问题描述

我想找到两个具有原始顺序的列表的交集。因此,如果

a = [2, 3, 5, 6]
b = [17, 28, 2, 8, 0, 3]

我需要[2, 3]。但是对于[3, 2, 5, 6][17, 28, 2, 8, 0, 3]我需要[2]

我怎样才能得到它?

标签: pythonintersection

解决方案


def inter(a,b):
    c = []
    for num in a:
        if num in b and (not len(c) or b.index(c[-1]) < b.index(num)):
            c.append(num)
    return c

推荐阅读