2012-08-01 106 views
11

我在做一个排名类型的事情,会发生什么是我比较分数与当前分数,如果分数低于当前那么玩家得到了高分,但是当使用这个这里的代码大于小于,蟒蛇

 print "Score = " + str(score) + ", Compared to = " + str(array[x]) 
     if score < array[x]: 
       #Do stuff here 

但即使score是4,array [x]是2,if语句仍然完成?

我做错了什么?

我的理解是,如果score 4和array [x]是2,那么4是大于2,这意味着它返回False?


赫雷什的完整代码

def getRank(array, score): 
    rank = 0 
    rankSet = False 
    for x in range(0, len(array)): 
     print "Score = " + str(score) + ", Compared to = " + str(array[x]) 
     if score < array[x]: 
      if not rankSet: 
       rank = x 
       print "Set rank to: " + str(rank) 
       rankSet = True 
     elif score == array[x] or score > array[x]: 
      rank += 1 
      print "Rank higher than " + str(x) 
    print "Rank = " + str(rank) 
    return rank 

它打印这一点,如果得分= 4和阵列是由[1,2]

Score = 4, Compared to = 1 
Set rank to: 0 
Score = 4, Compared to = 2 
Rank = 0 

回答

21

检查以确保两个score和array [x]是数字类型。您可能会将整数与字符串进行比较......这在Python 2.x中是令人心碎的。

>>> 2 < "2" 
True 
>>> 2 > "2" 
False 
>>> 2 == "2" 
False 

编辑

进一步说明:How does Python compare string and int?

+3

最简单的方法来检查:'打印再版(评分),再版(阵列[X])'。另外:在Python 3中,你会得到'TypeError:无法定义的类型:int() Dougal 2012-08-01 21:33:16

+0

为什么我没有想到那个D:我想我可能是 – FabianCook 2012-08-01 21:33:28

+0

使用'print type(score)'它回来了''但我认为它是这样做的数组。 – FabianCook 2012-08-01 21:35:11