我有一个列表,我们称之为列表,如下所示:
[[Redditor(name='Kyle'), Redditor(name='complex_r'), Redditor(name='Lor')],
[Redditor(name='krispy'), Redditor(name='flyry'), Redditor(name='Ooer'), Redditor(name='Iewee')],
[Redditor(name='Athaa'), Redditor(name='The_Dark_'), Redditor(name='drpeterfost'), Redditor(name='owise23'), Redditor(name='invirtibrit')],
[Redditor(name='Dacak'), Redditor(name='synbio'), Redditor(name='Thosee')]]
该列表有1000个元素(或列表)。我试着将其中的每一个与其他列表成对地进行比较,并试着得到每一对列表的公共元素的数量。执行此操作的代码:
def calculate(list1,list2):
a=0
for i in list1:
if (i in list2):
a+=1
return a
for i in range(len(thelist)-1):
for j in range(i+1,len(thelist)):
print calculate(thelist[i],thelist[j])
我的问题是:该函数的计算速度非常慢,根据列表对的长度,每个列表对需要2秒或更多的时间。我猜,这和我的列表结构有关。我错过了什么?你知道吗
首先,我建议将类设置为可哈希的,这里引用了:What's a correct and good way to implement __hash__()?
然后,可以通过执行以下操作使列表列表成为集合列表:
那么你的功能就会运行得更快!你知道吗
相关问题 更多 >
编程相关推荐