我找到了一个关于此问题的帖子,但是没有运气好。
min = 9
max = 10
a = ['8','9','10','11']
for x in a:
if max >= x > min:
print 'one'
else:
d = (max >= x > min)
print d, x
if (x > min >= max):
#if (min < x >= max):
print x
else:
print x, ' is equal to or greater than', max
输出:
False 8
8 is equal to or greater than 10
False 9
9 is equal to or greater than 10
False 10
10 is equal to or greater than 10
False 11
11 is equal to or greater than 10
此线程working code?表示语法需要:
if 10000 <= number <= 30000:
pass
我已经尝试了我能想到的各种标志组合,并且所有人的回报总是正确或错误,这是错误的。
我也试过这个(更长的)代码:
min = 9
max = 10
a = ['8','9','10','11']
for x in a:
print 'X is:', x
if int(x) == max:
print 'max found:', x
elif int(x) < max:
if int(x) > min:
print 'min:', x
elif int(x) < min:
print 'under range', x
else:
print 'out of range', x
输出也出乎意料,因为我希望能抓住所有情况:
X is: 8
X is: 9
X is: 10
max found: 10
X is: 11
out of range 11
唉!我如何“正确”检查所有项目并在我的最小值,最大值下返回?
答案 0 :(得分:0)
你需要比较int,int或str,str。过去我会建议bisect
给你插入点。
例如:
import bisect
minint, maxint = 9, 10
a = ['8','9','10','11']
b = [int(x) for x in a]
minidx = bisect.bisect_left(b, minint)
maxidx = bisect.bisect_left(b, maxint)
print('below:', a[0:minidx])
print('between:', a[minidx:maxidx])
print('above:', a[maxidx:])
输出:
below: ['8']
between: ['9']
above: ['10', '11']
根据您在每个端点定义比较<=
或<
的方式,您需要应用bisect_left
或bisect_right
如果我们将第一个bisect
更改为right
:
import bisect
minint, maxint = 9, 10
a = ['8','9','10','11']
b = [int(x) for x in a]
minidx = bisect.bisect_right(b, minint)
maxidx = bisect.bisect_left(b, maxint)
print('below:', a[0:minidx])
print('between:', a[minidx:maxidx])
print('above:', a[maxidx:])
输出更改并显示9到10之间没有任何内容
below: ['8', '9']
between: []
above: ['10', '11']