【问题标题】:Pairwise comparison in list of lists taking too long列表列表中的成对比较耗时太长
【发布时间】:2018-04-04 09:56:18
【问题描述】:

我有一个列表列表,我们称之为列表,看起来像这样:

[[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')]]

thelist 有 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 秒或更长时间,具体取决于它们的长度。我猜,这与我的列表结构有关。我在这里错过了什么?

【问题讨论】:

  • 将此转换为使用集合而不是列表。然后应用集合交集,并返回结果的长度。您能否提供一个独立的示例供我们进行实验?
  • Redditor 对象是否可散列?
  • 要跟进@Prune 的评论,我建议检查Redditor 类,看看它是否可以散列。
  • 您的列表组织背后有什么方法吗?它可以确定是否有更好的方法来查找值。
  • @Prune 谢谢。使用集合列表而不是列表列表完全解决了问题

标签: python performance list search


【解决方案1】:

首先,我建议您将您的课程设置为可散列,此处引用:What's a correct and good way to implement __hash__()?

然后,您可以通过执行以下操作使列表列表成为集合列表:

thelist = [set(l) for l in thelist]

那么你的函数会运行得更快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多