簡體   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