Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找排序列表中两个数字之间是否存在数字的更好方法_Python_List_Sorting - Fatal编程技术网

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)之间:#介于
之间<代码>其他:#不匹配