python的列表、元组和for循环

2024-04-26 07:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单:

a=[1, 2, 3, 300] # this is IDs of workers 

以及元组列表:

f=[(1, 1, 1), (1, 0, 0), (0, 0, 0), (1, 500, 600)]

对于a(a[i])中的每个元素,它在f(f[i])中都有一个相关元素(元组)。所以我需要对f[i]中每一个a[i]的元素求和,直到根据用户的不同得到某些索引。例如,如果用户希望求和结束到某个索引(比如2),那么输出将是ID 1=a[0]-->;总和将为2(f[0]=1+f[1]=1),对于ID 2=a[2]-->;求和为1[f[0]=0+f[1]=1],依此类推直到a[3] 这是我的密码:

str1=int(input('enter the index[enter -->1/2/3]'))
a=[1, 2, 3, 300]
f=[(1, 1, 1), (1, 0, 0), (0, 0, 0), (1, 500, 600)]
length=len(a)
temp=0 #sum
for i in range(0,length):
    y=a[i]
    att_2=f[i]
    print("{} {}".format("The worker ID is ", y))
    for z in range(0,(str1)):
        temp=temp+att_2[i]
        print(temp) # tracing the sum

对于某个a[I],我得到了一个错误加上错误的结果:

enter the index[enter -->1/2/3]2
 temp=temp+att_2[i]
IndexError: tuple index out of range
The Student ID is  1
1
2
The Student ID is  2
2
2
The Student ID is  3
2
2
The Student ID is  300

Process finished with exit code 1

我正试图纠正这些错误,但找不到原因。谢谢


Tags: ofthe用户id元素indexis错误
1条回答
网友
1楼 · 发布于 2024-04-26 07:42:52

您的错误是因为您混淆了变量i和变量z

代码使用变量i在元组中循环,这将导致错误,因为为另一组指令计算了i将采用的最大值

第11行的变量切换将解决您的问题

原件:

str1=int(input('enter the index[enter  >1/2/3]'))
a=[1, 2, 3, 300]
f=[(1, 1, 1), (1, 0, 0), (0, 0, 0), (1, 500, 600)]
length=len(a)
temp=0 #sum
for i in range(0,length):
    y=a[i]
    att_2=f[i]
    print("{} {}".format("The worker ID is ", y))
    for z in range(0,(str1)):
        temp=temp+att_2[i]
        print(temp) # tracing the sum

新的:

str1=int(input('enter the index[enter  >1/2/3]'))
a=[1, 2, 3, 300]
f=[(1, 1, 1), (1, 0, 0), (0, 0, 0), (1, 500, 600)]
length=len(a)
temp=0 #sum
for i in range(0,length):
    y=a[i]
    att_2=f[i]
    print("{} {}".format("The worker ID is ", y))
    for z in range(0,(str1)):
        temp=temp+att_2[z]
        print(temp) # tracing the sum

相关问题 更多 >