假设我有三个列表,如
course=[("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")]
grade= [("UGM2018001", "MA101", "AB"), ("UGP2018132", "PH101", "B"), ("UGM2018001", "PH101", "B")]
student= [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")]
我想打印输出
r=[('UGM2018001', 'Rohit Grewal', [('MA101', 'Calculus', 'AB'), ('PH101', 'Mechanics', 'B')]), ('UGP2018132', 'Neha Talwar', [('PH101', 'Mechanics', 'B')])]
我该怎么做?
答案 0 :(得分:0)
可以有更高级的zip
选项,但这里是如何使用标准循环来实现的。唯一需要注意的是如何将列表附加到元组,即使用myTuple+(myList,)
或myTuple+tuple([myList])
,而不是myTuple+tuple(myList)
或myTuple+tuple(myList)
。
course=[("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")]
grade= [("UGM2018001", "MA101", "AB"), ("UGP2018132", "PH101", "B"), ("UGM2018001", "PH101", "B")]
student= [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")]
final = []
for s in student:
temp = []
for g in grade:
for c in course:
if s[0] in g and g[1] in c:
t = c+(g[2],)
temp.append(t)
final.append(s + (temp,))
print final
结果:
[('UGM2018001', 'Rohit Grewal', [('MA101', 'Calculus', 'AB'), ('PH101', 'Mechanics', 'B')]), ('UGP2018132', 'Neha Talwar', [('PH101', 'Mechanics', 'B')])]