【问题标题】:Greater than less than, python大于小于,python
【发布时间】:2012-08-01 21:29:54
【问题描述】:

我正在做一个排名类型的事情,我将分数与当前分数进行比较,如果分数低于当前分数,则玩家获得了高分,但是在这里使用此代码时

        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

如果 score = 4 并且数组由 [1, 2] 组成,则打印此内容

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

【问题讨论】:

    标签: python if-statement


    【解决方案1】:

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

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

    编辑

    进一步解释:How does Python compare string and int?

    【讨论】:

    • 最简单的检查方法:print repr(score), repr(array[x])。另外:在 Python 3 中,你会得到 TypeError: unorderable types: int() &lt; str();这只是 2.x 的问题。
    • 为什么我没有想到那个D:我想我可以
    • 使用 print type(score) 它返回 &lt;type 'int'&gt; 但我认为它的数组正在这样做。
    • @Dougal - 感谢您的澄清!在可预见的未来,我被困在 2.x 领域:p 答案已更新。
    • 我们走了print type(array[x]) 回来了&lt;type 'str'&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多