如何从字符串元组列表中访问每个字符串并合并它?

时间:2018-03-05 14:33:30

标签: python list tuples

假设我有三个列表,如

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')])]

我该怎么做?

1 个答案:

答案 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')])]