Python 查找排序列表中两个数字之间是否存在数字的更好方法
我有一个这样的分类列表Python 查找排序列表中两个数字之间是否存在数字的更好方法,python,list,sorting,Python,List,Sorting,我有一个这样的分类列表 s = [1 , 4 ,6 , 9 ,10 ] 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] 我想知道列表中是有一个数字,还是在两个数字之间。如果它出现在两个数字之间,我想把它们
s = [1 , 4 ,6 , 9 ,10 ]
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]
我想知道列表中是有一个数字,还是在两个数字之间。如果它出现在两个数字之间,我想把它们打印出来
现在我的代码是这样的
s = [1 , 4 ,6 , 9 ,10 ]
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]
对于s中的x:
如果b==x:\\b是数字
打印b
如果b>x和b
有更好的方法吗?正是这样做的:
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]
这不是完美的优化,但您可以避免多次使用index()方法
for i,j in enumerate(s,1):
if b == j: \\ b is the number
print b
elif b > j and b < s[i+1] and s[i] < len(s):
print b , s[i + 1]
枚举中i,j的:
如果b==j:\\b是数字
打印b
如果b>j和b
如果b=11
,你的预期行为是什么?@manoj只需小心左二等分()
是0
还是len
。。。例如:x=11
给出了11介于[10]和[]之间
所以可能:elif n不在(0,len)之间:#介于
之间<代码>其他:#不匹配