python - 查找一个数字是否存在于列表指定的数字范围之间

标签 python

我有一个列表:

timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']

目标数:

ptime = 1377091810

我想找到 ptime 位于哪一对时间戳之间。例如在这种情况下,它位于第一个和第二个时间戳之间。所以我想返回值 1377091800 作为所需的输出。 同样,如果 ptime1377091520,那么我希望返回第三个时间戳,即 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/

相关文章:

python - 将(来回)UNIX 时间戳转换为 pandas.tslib.Timestamp 和系列的日期时间

python - 使用排序技术时出现类型错误

python - 如何从具有许多不同前景的图像中提取任意背景矩形 block

python - seaborn 置信区间计算正确吗?

python - 记录到两个不同的 .log 文件

python - 基于元素包含在二进制矩阵中的快速数组操作

python - 使用 "bag of usual phrases"查找不寻常的短语

python - 访问 pandas 数据框中单行的推荐方法?

python - Pandas 数据框到列表字典

python - 如何在 Ubuntu 16.04 上完全卸载 python 2.7.13