我有一个看起来像这样的元组列表:
[(334.99972431901307, 0.0), (335.00088248902574, 0.0), (335.0020406650446, 0.0), (335.0031988470696, 66.83868408203125), (335.00435703510072, 252.91905212402344), (335.0055152291381, 341.447509765625), (335.00667342918183, 282.1964111328125), (335.0078316352317, 125.92335510253906), (335.00898996725408, 0.0), (335.01014818531672, 0.0)]
该列表的长度为 16665,并按每个元组的第一个元素排序。我想根据第一个元组值从列表中提取一定范围的元组。目前我这样做:
def getSpectra_mzWindow(self, mzStart, mzEnd):
for spectrum in self.mzmlInstance:
# loop through all the peaks
for peak in spectrum.peaks:
# it's ordered, so when peak[0] > mzEnd it can stop
if float(peak[0]) > mzEnd:
break
if mzStart <= float(peak[0]) <= mzEnd:
yield spectrum, peak
但是,这非常慢。既然我知道它是按第一个值排序的,有没有比遍历整个列表更快的方法呢?我正在考虑实现二进制搜索,但是是否已经有一个库对排序的元组列表进行了优化?