python - 高效的 Python 搜索算法,用于在移动时间间隔内查找匹配项

标签 python algorithm dictionary

我有如下字典列表:

listofdicts = [{'Time':2015-03-14 11:54:00, 'Value':'Some Value'},
               {'Time':2015-03-14 13:23:00, 'Value':'Another Value'},
               {'Time':2015-03-14 12:52:00, 'Value':'Some Value'}, ...]

我想在列表中搜索符合以下条件的词典: 查找三个或更多具有相同 Value 值且 Time 值彼此相差在 10 分钟以内的字典。我希望此算法在每个符合此条件的字典中创建一个新键并将其标记为匹配。

e.g. The search algorithm would find:
{'Time':2015-03-14 11:54:00, 'Value':'Same Value'}
{'Time':2015-03-14 11:56:00, 'Value':'Same Value'}
{'Time':2015-03-14 11:52:00, 'Value':'Same Value'}
and add the matching key to each dictionary:
{'Time':2015-03-14 11:54:00, 'Value':'Same Value', 'Matching':'True'}
{'Time':2015-03-14 11:56:00, 'Value':'Same Value', 'Matching':'True'}
{'Time':2015-03-14 11:52:00, 'Value':'Same Value', 'Matching':'True'}

我已经创建了一个算法来执行此操作,但它不是特别有效或可扩展。任何人都可以就如何让它变得更好或需要研究的研究领域提供任何建议吗?

当前算法:

for dict in listofdicts:
   matchingdicts = []
   for dict2 in listofdicts:
      if dict['Value']==dict2['Value']:
         matchingdicts.append(dict2)
   listoftimeintervals = 
      [[dict['Time'] - datetime.timedelta(minutes=10),dict['Time']],
       [dict['Time'] - datetime.timedelta(minutes=9),dict['Time'] + datetime.timedelta(minutes=1)],
       ...,
       [dict['Time'],dict['Time'] + datetime.timedelta(minutes=10)]]
   for time in listoftimeintervals:
      dictsintimerange = []
      for matchingdict in matchingdicts:
         if time[0]<=matchingdict['Time']<=time[1]:
            dictsintimerange.append(matchingdict)
      if len(dictsintimerange)>=3:
         for eachdict in dictsintimerange:
            eachdict['Matching']=='True'

最佳答案

(注意:我什至没有通过解释器运行这段代码。)

首先按值对字典进行分区。

import collections
listofdictsbyvalue = collections.defaultdict(list)
for d in listofdicts:
    listofdictsbyvalue[d['Value']].append(d)

然后按时间对每个列表进行排序并浏览。

import operator
k = 3
for lst in listofdictsbyvalue.values():
    lst.sort(key=operator.itemgetter('Time'))
    for i in range(len(lst) - (k - 1)):
        if lst[i + (k - 1)]['Time'] - lst[i]['Time'] <= datetime.timedelta(minutes=10):
            for j in range(i, i + k):
                lst[j]['Matching'] = 'True'

关于python - 高效的 Python 搜索算法,用于在移动时间间隔内查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29100401/

相关文章:

python - 在Windows中安装Jupyter Notebook

python - 具有附加参数的 PyQt5 QPushbutton

python - 我可以在删除每个组中的第一个和最后一个条目的同时使用 Pandas group by 吗?

python - Kosaraju 的 scc 算法

swift - 在 Swift 中使用 Maps 返回数组的数组,有人可以确认我对这段代码的理解吗?

python - 计算字典键中值重复的次数

python - 如何在 Windows 上的 docker 中的 django 中运行测试期间修复 'TypeError: isinstance() arg 2 must be a type or tuple of types'

c++ - 解决类似 Flood-It 难题的最少点击次数

python - Python中最小值和最大值的大O

python - 将Python字典中的元素移动到另一个索引