首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python中测试这两个数字是正数还是负数

在Python中测试这两个数字是正数还是负数
EN

Stack Overflow用户
提问于 2014-04-01 03:19:18
回答 4查看 4.9K关注 0票数 2

我正在比较数字列表,并为匹配方向分配“分数”。每一次正面或负面的比赛都应该使参与者的得分增加1。

例如:

代码语言:javascript
运行
复制
list1 =[5.6, -7.1, 6.4]
list2 =[4.5, -2.0, -4.2]

应该给参与者打2分,因为5.6和4.5都是正(+1),-7.1和-2.0都是负(+1)。

我让它可以很好地比较积极的东西:

代码语言:javascript
运行
复制
def score2(list1, list2):
    count = 0
    for index in range (0, len(list1)):
        if list1[index] and list2[index] > 0:
            count += 1
        return count

尽管-7.1和-2.0都是负的,但负片的部分仍然返回0。在前面的函数中,我将其作为elif部分,但我将其分离以进行调试:

代码语言:javascript
运行
复制
def score3(list1, list2):
    count = 0
    for index in range (0, len(list1)):
        if list1[index] and list2[index] < 0:
            count += 1
        return count

有趣的是,如果我这么做了

代码语言:javascript
运行
复制
print list1[1] and list2[1] < 0

它可以打印True。所以我不确定score3到底出了什么问题。

EN

Stack Overflow用户

发布于 2014-04-01 03:20:50

list1[index] and list2[index] < 0的意思是list1[index] and (list2[index] < 0)and适用于list1[index]list2[index] < 0的结果。要了解andor的工作原理,请参阅the documentation。你想要的是:

代码语言:javascript
运行
复制
list1[index] < 0 and list2[index] < 0

在您的第一个示例测试中也发生了同样的情况,但是您没有注意到它,因为它恰好可以工作。对于这种情况,您同样应该这样做:

代码语言:javascript
运行
复制
list1[index] > 0 and list2[index] > 0
票数 3
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22770274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档