Python双循环

Tar*_*zan 0 python numpy python-3.x

我的循环遇到了麻烦.我得到一个400超出范围的错误.我申请的是不允许的,或者我的问题是什么?它对我来说看起来像法律语法?

survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 5

你将值与索引混淆了.在Python中,for x in ...语法返回可迭代对象中的每个元素,而不是索引.试试这个:

for t in survTime:
     for a in age:
        if t > 365 and a < 50:
        # and so on
Run Code Online (Sandbox Code Playgroud)

请注意,您打算迭代每个数组的,但实际上您将每个项目用作索引,这是超出范围的 - 例如:survTime没有400元素!为了完整起见:如果你真的需要索引,遍历名单的方法lst将是:

for i in range(len(lst)):
    ele = lst[i] # do something with the element
Run Code Online (Sandbox Code Playgroud)