我正在比较数字列表,并为匹配方向分配“分数”。每一次正面或负面的比赛都应该使参与者的得分增加1。
例如:
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)。
我让它可以很好地比较积极的东西:
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部分,但我将其分离以进行调试:
def score3(list1, list2):
count = 0
for index in range (0, len(list1)):
if list1[index] and list2[index] < 0:
count += 1
return count有趣的是,如果我这么做了
print list1[1] and list2[1] < 0它可以打印True。所以我不确定score3到底出了什么问题。
发布于 2014-04-01 03:20:50
list1[index] and list2[index] < 0的意思是list1[index] and (list2[index] < 0)。and适用于list1[index]和list2[index] < 0的结果。要了解and和or的工作原理,请参阅the documentation。你想要的是:
list1[index] < 0 and list2[index] < 0在您的第一个示例测试中也发生了同样的情况,但是您没有注意到它,因为它恰好可以工作。对于这种情况,您同样应该这样做:
list1[index] > 0 and list2[index] > 0https://stackoverflow.com/questions/22770274
复制相似问题