我正在尝试寻找一种更优雅的方式在表格中查找数字。
例如:A列的值为13,B列的值为9.8。13大于第4行的最大行,所以我查看第4行B列,并将该数字与我的B列编号进行比较。根据我的B列编号是大于还是小于第4行B列,我会做一些事情。
这就是我到目前为止所拥有的,但它看起来很混乱。有没有一种方法可以将所有的浮点数存储在一个列表或字典中,以使它看起来更好?除了逐字比较每个浮点数之外,我似乎找不到一种方法来查看一个浮点数是否在另一个浮点数之间。
table = []
someOtherFloat = 13.0
someFloat = 9.8
if someOtherFloat >= 21.2:
table.insert(2, 25.4)
if someFloat >= 25.4:
print 'something'
else:
print 'something'
elif 18.8 <= someOtherFloat < 21.2:
if someFloat >= 21.9:
print 'something'
else:
print 'something else'
table.insert(2, 21.9)
elif 14.2 <= someOtherFloat < 18.8:
if someFloat >= 14.7:
print 'something'
else:
print 'something else'
table.insert(2, 14.7)
elif 9.0 <= someOtherFloat < 14.2:
if someFloat >= 10.4:
print 'something'
else:
print 'I should get printed by this code' # <--------------
table.insert(2, 10.4)
elif 5.7 <= someOtherFloat < 9.0:
if someFloat >= 7.0:
print 'something'
else:
print 'something else'
table.insert(2, 7.0)
elif 2.9 <= someOtherFloat < 5.7:
if someFloat >= 5.0:
print 'something'
else:
print 'something else'
table.insert(2, 5.0)
elif 0.6 <= someOtherFloat < 2.9:
if someFloat >= 3.5:
print 'something'
else:
print 'something else'
table.insert(2, 3.5)
else:
if someFloat >= 2.3:
print 'something'
else:
print 'something else'
table.insert(2, 2.3)
我尝试过执行以下操作,但不起作用。
checkme = [1.0, 2.3, 3.4]
checkme2 = ['hi', 'bye', 'hello']
def findBucket(aFloat):
for key in checkme:
if aFloat < key:
print checkme2[key]
return
print final
return
findBucket(3.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in findBucket
TypeError: list indices must be integers, not float
下面的代码似乎工作得最好
column_a = [21.2, 18.8, 14.2, 9.0, 5.7, 2.9, 0.6, -1.6]
column_b = [25.4, 21.9, 14.7, 10.4, 7.0, 5.0, 3.5, 2.3]
def findBucket(aFloat):
i = 0
while i < len(column_a):
if aFloat > column_a[i]:
print column_b[i]
return
i += 1
return
findBucket(18.9)
21.9
findBucket(13.2)
10.4
findBucket(2.7)
3.5
发布于 2018-07-17 07:16:53
您可以遍历字典,将操作映射到下限/上限,并与该字典进行比较:
# I used strings here which I print in the function, but you could very well
# assign methods as values.
checkme = {1.0:"hi!",2.3:"bye",3.4:"hello!"}
final = "goodbye"
def findBucket(aFloat):
for key in checkme.keys():
if aFloat < key:
print checkme[key]
return
# getting to this point means aFloat was greater than the last key
print final
return
替代解决方案,包含两个列表:
checkme = [1.0, 2.3, 3.4]
checkme2 = ['hi', 'bye', 'hello', 'finalanswer']
def findBucket(aFloat):
i = 0
while i < len(checkme):
if aFloat < checkme[i]:
print checkme2[i]
return
i += 1
print checkme2[-1] #negative indexing starts from the end of the list in python
return
https://stackoverflow.com/questions/51371169
复制相似问题