考虑一下在两个列表中给出的班级学生分数列表。
Students = ['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10']
Marks = [45, 78, 12, 14, 48, 43, 45, 98, 35, 80]在这两份名单中,学生获得了分数,Student1得到了Marks1等等,分数在>25百分位数<75百分位数之间,按分数的增加顺序排列。
我的问题--我们不能用python中的简单代码来解决这个问题吗?
在这之前我已经写好了密码。找出数字>25和<75,但无法按升序排列。排序()不起作用,排序也不起作用。请帮助提取特定数组值并分配给另一个数组以解决此问题。
for i in range(0,10):
if Marks[i]>25 and Marks[i]<75:
print(Students[i],Marks[i])
print(i)发布于 2020-03-01 14:32:14
在代码中添加一小部分可以解决这个问题,下面是解决方案
Students = ['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10']
Marks = [45, 78, 12, 14, 48, 43, 45, 98, 35, 80]
Students,Marks=zip(*sorted(zip(Students, Marks))) #addition to your code
for i in range(0,10):
if Marks[i]>25 and Marks[i]<75:
print(Students[i],Marks[i])发布于 2020-03-01 14:22:55
第25百分位数是“拿东西的人中的倒数第四位”,而第75位百分位数是“前四位数”,不管实际得分如何。因此,您需要做的是对列表进行排序,然后根据索引从中间取一片。
我觉得你想做的是:
import math
students = ['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10']
marks = [45, 78, 12, 14, 48, 43, 45, 98, 35, 80]
# zip() will bind together corresponding elements of students and marks
# e.g. [('student1', 45), ('student2', 78), ...]
grades = list(zip(students, marks))
# once that's all in one list of 2-tuples, sort it by calling .sort() or using sorted()
# give it a "key", which specifies what criteria it should sort on
# in this case, it should sort on the mark, so the second element (index 1) of the tuple
grades.sort(key=lambda e:e[1])
# [('student3', 12), ('student4', 14), ('student9', 35), ('student6', 43), ('student1', 45), ('student7', 45), ('student5', 48), ('student2', 78), ('student10', 80), ('student8', 98)]
# now, just slice out the 25th and 75th percentile based on the length of that list
twentyfifth = math.ceil(len(grades) / 4)
seventyfifth = math.floor(3 * len(grades) / 4)
middle = grades[twentyfifth : seventyfifth]
print(middle)
# [('student6', 43), ('student1', 45), ('student7', 45), ('student5', 48)]这里有10名学生,所以你如何绕过twentyfifth和seventyfifth取决于你自己(我选择把那些严格在25%-75%以内的学生包括在内,用四舍五入的‘内向’-你可以通过切换ceil和floor来做相反的事情,在这个例子中,你可以得到你的最终列表中有两个元素--或者你可以用同样的方式对它们进行舍入)。
发布于 2020-03-01 14:40:57
看来@Green Cloak Guy的答案是正确的。但是不管怎么说,如果你想得到学生的数据,分数在两个范围之间,我会这样做:
# Get a dict of students with it's mark, filtered by those with mark between 25 and 75
students_mark = {s: m for s, m in zip(Students, Marks) if m > 25 and m < 75}
# Sort results
res = dict(sorted(students_mark.items(), key=lambda i: i[1])
# res: {'student9': 35, 'student6': 43, 'student1': 45, 'student7': 45, 'student5': 48}
# In one line
res = {s: m for s, m in sorted(zip(Students, Marks), key=lambda i: i[1]) if m > 25 and m < 75}总结:首先将每个学生的分数连接起来,然后过滤和排序。我把结果存储为字典,因为它似乎更方便。
https://stackoverflow.com/questions/60475885
复制相似问题