繁体   English   中英

如何获取元组或列表元素的索引,该元素本身就是列表的元素

[英]how to get an index of an element of tuple or list which itself is an element of a list

代码:

 Cour_det = [("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")];
 Stu_det = [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")];
 Grades = [("UGM2018001", "MA101", "AB"),("UGP2018132", "PH101", "B"),
 ("UGM2018001", "PH101", "B")];
 Cour_det = sorted(Cour_det, key = lambda x : x[0]);
 Stu_det = sorted(Stu_det, key = lambda x : x[0]);
 Grades = sorted(Grades, key = lambda x : x[1]);
 Grades = sorted(Grades, key =lambda x : x[0]);
 B={}
 #code by which i tried to add grade to nested list
 for i in range(len(Stu_det)):
     for j in range(len(Cour_det)):
         B[Stu_det[i][0]][Cour_det[j][0]]=(Cour_det[j][1],Grades[][])
         #here i am stuck on how to access grade of the course that i am adding
 #it should look like this
 B={"UGM2018001":{"MA101":("Calculus","AB'),"PH101":("Mechanics","B")}}
 #above list for roll no UGM2018001,similarly other roll no.s as keys and
 #course code can be keys of nested list for those roll no.s

在此代码中,我想制作一个嵌套字典,其中外键将成为roll no,如List Stu_det的每个元组的第一个元素是哪个( 例如UGM2018001) ,然后嵌套键将是课程代码( 例如MA101 )和然后每个嵌套键的元素将是一个元组或列表,其中将包含两个元素,第一个元素将是课程名称( 例如微积分 ),第二个元素是我想要提及的等级( 例如AB ),但是访问该等级已成为问题,如何访问它或获取它的索引。 取得第No卷后,我无法获得学科等级。 和课程代码键。

这是使用defaultdict模块执行此操作的方法。

# load library
from collections import defaultdict

# convert to dictionary as this will help in mapping course names
Cour_det = dict(Cour_det)
Stu_det = dict(Stu_det)


# create a dictionary for grades
grades_dict = defaultdict(list)
for x in Grades:
    grades_dict[x[0]].append(x[1:])

# create a new dict to save output
new_dict = defaultdict(dict)

# loop through previous dictionary and replace course codes with names
for k,v in grades_dict.items():

    for val in v:
        temp = list(val)
        temp[0] = Cour_det[temp[0]]
        new_dict[k].update({val[0]: tuple(temp)})

# print output        
print(new_dict)
defaultdict(dict,
        {'UGM2018001': {'MA101': ('Calculus', 'AB'),
          'PH101': ('Mechanics', 'B')},
         'UGP2018132': {'PH101': ('Mechanics', 'B')}})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM