[英]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.