我是python編程的新手。Python中兩個浮點值之間的比較
我已經寫了一些簡單的Python代碼,如下圖所示:
#!/usr/bin/python
import sys
def reducer():
bigSale = 0
oldKey = None
for line in sys.stdin:
data = line.strip().split("\t")
if len(data) != 2:
continue
thisKey, thisSale = data
print oldKey,bigSale,thisKey,thisSale
if not oldKey:
oldKey = thisKey
bigSale = thisSale
print "This is first if and value of oldKey and bigSale are ",oldKey," ",bigSale
elif oldKey and oldKey != thisKey:
print "{0}\t{1}".format(oldKey, bigSale)
oldKey = thisKey
bigSale = 0
elif(oldKey and oldKey == thisKey and thisSale > bigSale):
print "Observe the expression : ", thisSale, " > " , bigSale , " has a boolean value of ", thisSale > bigSale
print "This is the second elif construct and value of bigSale before assignment is ",bigSale
bigSale = thisSale
print "This is the second elif construct and value of bigSale after assignment is ",bigSale
print "Now the new value of oldKey and bigSale are: ",oldKey," ",bigSale
if oldKey != None and thisSale > bigSale:
print "{0}\t{1}".format(oldKey, bigSale)
def main():
reducer()
main()
我傳遞以下數據作爲輸入:
Anchorage 22.36
Anchorage 298.86
Anchorage 6.38
Aurora 117.81
Austin 327.75
Austin 379.6
Austin 469.63
Boston 418.94
Buffalo 483.82
Chandler 344.09
Chandler 414.08
Chicago 31.08
Corpus Christi 25.38
Fort Wayne 370.55
Fort Worth 153.57
Fort Worth 213.88
Fremont 222.61
Fresno 466.64
Greensboro 290.82
Honolulu 345.18
Houston 309.16
Indianapolis 135.96
Las Vegas 53.26
Las Vegas 93.39
Lincoln 136.9
Madison 16.78
Minneapolis 182.05
Newark 39.75
New York 296.8
Norfolk 189.01
Omaha 235.63
Omaha 255.68
Philadelphia 351.31
Pittsburgh 475.26
Pittsburgh 493.51
Portland 108.69
Reno 80.46
Reno 88.25
Riverside 15.41
Riverside 252.88
San Bernardino 170.2
San Diego 66.08
San Francisco 260.65
San Jose 214.05
San Jose 215.82
Spokane 287.65
Spokane 3.85
Stockton 247.18
Tulsa 205.06
Virginia Beach 376.11
當我看到調試語句的幫助下輸出,我發現預期
請看以下輸出我得到的片段時,我對樣本數據運行的代碼,浮動比較是沒有發生:
無0安克雷奇22.36 這是第一,如果和oldKey和bigSale的值是安克雷奇22.36 安克雷奇22.36安克雷奇298.86
觀察表達式:298.86 > 22.36
具有真 這是第二個elif
構建體和的值的布爾值bigSale之前的任務是22.36
這是bigSale的分配之後的第二elif
結構和值298.86
現在oldKey和bigSale的新價值:安克雷奇298.86 安克雷奇298.86安克雷奇6.38
觀察表達式:6.38> 298.86具有真
布爾值這被分配之前bigSale的第二elif的構建體和值是298.86
這是第二elif構造和賦值後bigSale的值是6.38 現在oldKey和bigSale的新值是:Anchorage 6.38
任何人都可以請幫助我,我在哪裏做錯了?
對不起樣本輸出的不良壓痕提供: 請參考下面與合適的樣品輸入縮進: 安克雷奇22.36 安克雷奇298.86 安克雷奇6.38 極光117.81 奧斯汀327.75 奧斯汀379.6 奧斯汀469.63 波士頓418.94 布法羅483.82 錢德勒344.09 錢德勒414.08 芝加哥31.08 – user2481001