Man*_*noj 3 python sorting list
我有一个像这样的排序列表
s = [1 , 4 ,6 , 9 ,10 ]
Run Code Online (Sandbox Code Playgroud)
我想知道列表中是否存在数字,或者两个数字之间是否存在数字.如果它出现在两个数字之间,我想打印出来.
现在我的代码看起来像这样
for x in s:
if b == x: \\ b is the number
print b
elif b > x and b < s[s.index(x) + 1] and s.index(x) < len(s):
print b , s[s.index(x) + 1]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
bisect模块正是这样做的:
s = [1 , 4 ,6 , 9 ,10 ]
import bisect
x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
print x, 'is in the list'
else:
print x, 'comes between', s[n-1:n], 'and', s[n:n+1]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
555 次 |
| 最近记录: |