获取基于特定项目的先前值

use*_*084 3 python python-2.7

我正在尝试一个脚本,我们使用列表项,然后我将获得前一项.

lst = [1, 3, 4, 6, 8, 10]

next_item = next((x for x in lst if x > 6), None)
print next_item #8
Run Code Online (Sandbox Code Playgroud)

此代码适用于6之后的项目.但是我需要6之前的项目.

我正在寻找一个prev方法的文档,但我找不到任何相关的东西.有什么想法吗?

小智 5

假设"之前"是指"之前lst",则没有必要使用这种复杂的方式.这个

lst[lst.index(6) - 1]
Run Code Online (Sandbox Code Playgroud)

会给

4
Run Code Online (Sandbox Code Playgroud)

而这个

lst[lst.index(6) + 1]
Run Code Online (Sandbox Code Playgroud)

会给

8
Run Code Online (Sandbox Code Playgroud)

当然,您应该检查索引超出范围的错误.