简体   繁体   English

我如何在不使用集合的情况下在python中找到两个列表的交集

[英]How would I find the intersection of two lists in python without using sets

I have a program with two very large lists, one with 3^12 terms and the other with 5000 terms, and I want to find the intersection of them (items that are the same in both lists). 我有一个包含两个非常大的列表的程序,一个具有3 ^ 12个术语,另一个具有5000个术语,并且我想找到它们的交集(两个列表中的项目都相同)。

I have already tried using sets and loops(see below). 我已经尝试过使用集合和循环(见下文)。

I have tried (in Python 3) 我已经尝试过(在Python 3中)

[i for i in joinedCombs if i in dictionary]

and

endResult = list(set(joinedCombs)&set(dictionary))

I get a time error for the first line of code and a memory error for the second line of code. 第一行代码出现时间错误,第二行代码出现内存错误。 What could I do to balance out speed and time? 我该怎么做才能平衡速度和时间? Please leave an answer, not a comment 请留下答案,而不是评论

Use len to determine which list is the shorter one, and create a set from that: 使用len确定哪个列表是较短的列表,然后根据该列表创建一个集合:

[i for i in joinedCombs if i in dictionary]
if len(joinedCombs) < len(dictionary):
    s1 = set(dictionary)
    itr = joinedCombs
else:
    s1 = set(joinedCombs)
    itr = dictionary

new = [i for i in itr if i in s1]

您可以尝试以下代码行:

endResult = list(set(joinedCombs).intersection(dictionary))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:如果有重复项,如何查找两个列表的交集(实际上,我需要一个交集的长度)? - Python: how to find intersection of two lists (i need a lenght of intersection, actually) if there are duplicates? Python:列表/集合的交集 - Python: intersection of lists/sets Python 3.x-如何在两个字符串中查找字符集的交集 - Python 3.x - How to find the intersection of the sets of characters in two strings 如何查找列表的交集和并集(不使用集合) - How to find Intersection and Union of a List (without using sets) 在 Python 3 中使用 sys 查找两个排序的整数列表的交集 - Find the intersection of two sorted lists of integers using sys in Python 3 在python pandas数据框中为每一行查找两组列的交集,而不进行循环 - Find intersection of two sets of columns in python pandas dataframe for each row without looping 仅使用python列表(不设置)的列表交集算法实现 - list intersection algorithm implementation only using python lists (not sets) Python:两个列表列表的交集 - Python: Intersection of two lists of lists 在Python中,如何获取两个列表的交集,并保留交集的顺序? - In Python, how can I get the intersection of two lists, preserving the order of the intersection? 如何在Python中的两个列表的交集中选择元素 - How to select elements in the intersection of two lists in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM