簡體   English   中英

在python中運行循環有限的迭代

[英]run for loop limited iterations in python

我的對象列表非常大,我需要查找所有具有相同屬性的對象(any_object.any_attribute),然后將它們附加到新列表中。 因此,我對它們進行了預排序並運行了二進制搜索算法。 我發現了具有匹配屬性的對象,但問題是有多個這樣的對象(它們是鄰居),但是我想不出一種在這些連續對象上運行循環的干凈方法,因此它們都可以追加。 我的代碼粘貼在下面。

  low   = 0
  high  = len(sortedObjects)
  while low < high:
    mid = (low + high)/2
    if sortedObjects[mid].attr < desired_attr:
      low = mid + 1
    elif sortedSamples[mid].attr > desired_attr:
      high = mid
    else:
      newList.append(sortedObjects[mid])
      break

因此,我需要在最后一個else塊中編寫一些新代碼,該代碼將遍歷具有相同屬性的所有對象並將其追加。 聽起來像需要for循環,但是是否可以在有限的迭代中運行for循環,例如在C中?

我不想遍歷整個列表,因為那樣做會比較慢,並且此腳本的要求之一是必須快速高效。 它將在非常大的數據集上運行,我們正在考慮10-12小時的執行時間。 提前致謝!

嘗試這個:

else:
    # Find the first element that matches
    while mid > 0 and sortedSamples[mid - 1].attr == desired_attr:
        mid -= 1

    # Iterate until an element that doesn't match is found.
    while mid < len(sortedSamples) and sortedSamples[mid].attr == desired_attr:
        newList.append(sortedObjects[mid])
        mid += 1

它以O(m)時間運行,其中m是具有所需屬性的對象數。

如果要更頻繁地執行此搜索,則創建此屬性的列表:

attr_list = [o.attr for o in sortedObjects]

然后使用bisect模塊:

import bisect
left_i = bisect.bisect_left(attr_list, desired_attr)
right_i = bisect.bisect_right(attr_list, desired_attr, left_i)
newList = sortedObjects[left_i:right_i]

在else塊內運行第二個循環,從mid減少直到找到第一個對象,然后向前循環以獲取所有對象。 您可以通過保存舊的mid並在“向后循環”中找到它們時保存元素來加快速度,然后在向前循環之前再次向前跳轉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM