首页 > 解决方案 > 如何将相应的索引附加到列表

问题描述

我使用 for 循环和解包元组将一组学生过滤到三个存储桶中。我怎样才能将他们相应的学号附加到每个分数上?谢谢你。

#create index for 100 students, starting with 1
student_index = list(range(1,101))

#join index with results sheet
student_score_index = list(zip(student_index, results_sheet2))


group_a = []
group_b = []
group_c = []

# Iterate over pairs

for index, pair in enumerate(student_score_index):
    # Unpack pair: index, student_score
    index, score = pair
    # assign student scores into 3 buckets: group_a,group_b,group_c
    if score >= 60:
        group_a.append(score)
    elif score >= 50 and score <=59:
            group_b.append(score)
    else:
        group_c.append(score)

print(group_a)
[61, 67, 63, 62, 62, 62]

对于所有三个组,所需的结果应该是这样的:

#print corresponding student index number, score    

group_a = [(29,61),(51,67),(63,63),(65,62),(98,62),(99,62)]

标签: pythonfor-loopif-statementiterable-unpacking

解决方案


我不知道 score 或 group_a 等是什么......所以,这里我有一个例子 -

group_a = [61, 67, 63, 62, 62, 62]
score = [29,51,63,65,98,99,62]

new_lst = []
for i,j in zip(group_a,score):
    new_lst.append((j,i))

print(new_lst)

结果:

[(29, 61), (51, 67), (63, 63), (65, 62), (98, 62), (99, 62)]

所以,你可以在你的代码中实现它


推荐阅读