我有一个列表:
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
目标数:
ptime = 1377091810
我想找到 ptime
位于哪一对时间戳之间。例如在这种情况下,它位于第一个和第二个时间戳之间。所以我想返回值 1377091800
作为所需的输出。
同样,如果 ptime
是 1377091520
,那么我希望返回第三个时间戳,即 1377091500
,因为它位于第三个和第四个时间戳之间。
我的代码:
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
ptime = 1377091810
for idx, value in enumerate(timestamp_list):
val = long(value)
if idx!= len(timestamp_list)-1 and ptime >= val and ptime < long(timestamp_list[idx+1]):
target = val
break
elif (idx == len(timestamp_list)-1) and ptime >= val:
target = val
else:
pass
print target
输出:
1377091800
我想知道有什么优雅的解决方案吗?由于刚开始接触python,所以对python中的所有函数还不是很熟悉。
最佳答案
由于时间戳是排序的,你可以使用bisect
为此:
In [24]: timestamp_list = [1377091800, 1377093000, 1377094500, 1377095500]
In [25]: timestamp_list[bisect.bisect_right(timestamp_list, 1377093100)]
Out[25]: 1377094500
(我已将字符串转换为整数以保持代码清晰。)
关于python - 查找一个数字是否存在于列表指定的数字范围之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551848/