如何将相应的索引附加到列表

How can I attach the corresponding index to a list

我使用 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)]

我不知道分数是多少还是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)]

因此,您可以在代码中实现这一点

如果您愿意尝试一个新的库,pandas,我强烈推荐它。他们有专门用于此类工作的内置工具!

import pandas as pd

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

# join index with results sheet
score_index = pd.DataFrame.from_dict({
  "studentID": student_index,
  "scores": results_sheet2,
})

group_a = score_index.loc[score_index["score"] >= 60]
group_b = score_index.loc[score_index["score"] <= 59]
# etc ...

您实际上可以在使用 pandas 时进一步简化它,并执行以下操作:

import pandas as pd

# by default, pandas will generate an index to track each row, 
# for you. it's accessible by the `.index` property of `score_index`.
score_index = pd.DataFrame.from_dict({
  "scores": results_sheet2,
})

group_a = score_index.loc[score_index["score"] >= 60]
group_b = score_index.loc[score_index["score"] <= 59]
# etc ...