比较两个附加列表时如何使 for 语句起作用?

How can I make a for statement work when comparing two apended lists?

最后一个 for 语句不起作用。我正在比较两个函数的输出(每个函数都作为列表附加)。本质上,如果函数 A 列表中第一项的输出大于函数 B 列表中第一项的输出,那么我想打印 1,如果小于则我想打印 0,否则打印 0.5 .但是,当我 运行 时,我为每个值得到 1 的代码在两个列表中进行比较。这是错误的,因为我已经手动检查了每个值(应该有 1 和 0,没有 0.5)。

from IPython.lib.display import IFrame
#Exptected Value

import numpy as np
import math
natural_log = np.log(1)


Outcomes = [[20, 0],[ 20, 0],[ 20, 0],[ 20, 0],[ 20, 0]]

Probabilities = [[0.001, 0.999],[  0.01, 0.99],[  0.1, 0.9],[  0.25, 0.75],[  0.5, 0.5]]


Y = []
PT= []

for i in range(0,len(Outcomes)):
    Y.append(Outcomes[i][0]*Probabilities[i][0] + Outcomes[i][1]*Probabilities[i][1])
    
for i in range(0,len(Outcomes)):
    PT.append((math.exp(-(-np.log(Probabilities[i][0]))**0.5))*(Outcomes[i][0]**0.5)+(math.exp(-(-np.log(Probabilities[i][1]))**0.5))*(Outcomes[i][1]**0.5))

for i in range(0,len(Outcomes)):
        if PT > Y:
            print("gamble",i+1,"PT output = 1")
        if PT < Y:
            print("gamble",i+1,"PT output = 0")
        if PT ==Y:
            print("gamble",i+1,"PT output = 0.5")

print(PT)
print(Y)

尝试根据您的要求修改以下代码。

a=[1,2,3,4]
b=[1,3,2,1]

for i,j in zip(a,b):
    if i==j:
        print("it's a match.")
    else:
        print("not a match")

您需要建立索引才能访问 for 循环中的每个元素。否则,只比较列表的第一个元素。并且多次比较同一个值时,使用elif和else有助于提高程序的处理速度。

for i in range(0,len(Outcomes)):
    if PT[i] > Y[i]:
        print("gamble",i+1,"PT output = 1")
    elif PT[i] < Y[i]:
        print("gamble",i+1,"PT output = 0")
    else:
        print("gamble",i+1,"PT output = 0.5")