我试图找到一种更优雅的方式来查找表格中的数字。
示例: 我的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
答案 0 :(得分:1)
您可以遍历字典,将操作映射到下限/上限,并与该字典进行比较:
# 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
答案 1 :(得分:0)
import pandas as pd
def findBucket(aFloat):
df = pd.DataFrame({'A': [21.2,18.8,14.2,9,5.7,2.9,0.6,-1.6],
'B': [25.4,21.9,14.7,10.4,7,5,3.5,2.3]})
return(df.B.iloc[df.A.apply(lambda x: x if aFloat - x > 0 else 0).idxmax()])
说明: