Python交叉的两个列表保持重复 [英] Python intersection of two lists keeping duplicates

查看:208
本文介绍了Python交叉的两个列表保持重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个平面列表,其中一个列表包含重复的值。
例如,

  array1 = [1,4,4,7,10,10,10,15, 16,17,18,20] 
array2 = [4,6,7,8,9,10]

我需要在array1中找到也在array2中的值,在数组1中保持重复。
期望的结果将是

  result = [4,4,7,10,10,10] 

我想避免循环,因为实际的数组将包含超过数百万的值。
我已经尝试了各种设置和相交组合,但只是无法保留重复。



任何帮助将不胜感激!

解决方案

你的意思是不想使用循环?你将不得不以这种方式迭代。只需单独处理每个项目,并检查它是否在 array2 中:

  items = set(array2)
found = [i for array in array1如果我在项目中]






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

  found =(如果我在array2中,我在array1中为i)

所以你不必一次把所有的东西记忆在心。


I have two flat lists where one of them contains duplicate values. For example,

array1 = [1,4,4,7,10,10,10,15,16,17,18,20]
array2 = [4,6,7,8,9,10]

I need to find values in array1 that are also in array2, KEEPING THE DUPLICATES in array1. Desired outcome will be

result = [4,4,7,10,10,10]

I want to avoid loops as actual arrays will contain over millions of values. I have tried various set and intersect combinations, but just couldn't keep the duplicates..

Any help will be greatly appreciated!

解决方案

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.

这篇关于Python交叉的两个列表保持重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆