且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个列表的交集,在第一个列表中保留重复项

更新时间:2023-02-22 12:48:02

你不想使用循环是什么意思?您将不得不以一种或另一种方式对其进行迭代.只需单独接收每个项目并检查它是否在 array2 中:

What do you mean you don't want to use loops? You're going to have to iterate over it one way or another. Just take in each item individually and check if it's in array2 as you go:

items = set(array2)
found = [i for i in array1 if i in items]

此外,根据您将如何使用结果,考虑使用生成器:


Furthermore, depending on how you are going to use the result, consider having a generator:

found = (i for i in array1 if i in array2)

这样您就不必一次将整个内容全部记住.

so that you won't have to have the whole thing in memory all at once.