我编写了以下代码来查找列表中也在另一个列表中的元素。然而,这个算法在Big O中是n平方,是否有更好的解决方法? 提前谢谢
def printCommon(list1,list2):
for i in list1:
found = False
for j in list2:
if i == j:
print i
break
if __name__ == "__main__":
list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
printCommon(list1,list2)
答案 0 :(得分:0)
作为一种更有效的方式,您可以使用set.intersection
:
>>> set(list1).intersection(list2)
set([5])
替补标记:
from timeit import timeit
s1="""
def printCommon(list1,list2):
for i in list1:
found = False
for j in list2:
if i == j:
#print i
break
list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
printCommon(list1,list2)
"""
s2="""
list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
set(list1).intersection(set(list2))
"""
结果:
first: 0.129281997681
second : 0.0606861114502