Python,仅通过 1 个参数与 2 个列表相交,如果为 True,则附加第二个列表中的最后一个值

Python, intersect 2 lists only by 1 argument and if it is True, append last value from second list

试图找到如何通过“第一个参数”=音乐家 ID 来交叉 2 个列表的方法。 作为输出,我们需要获得 ID / Name / Lastname / Rating's place in first list / Rating's place in second list

示例:

["1", "Ad", "Rock", "1", "2"], ["2", "John", "Lennon", "2", "1"]

是否有更好的方法来按 ID 比较列表,如果它是 TRUE,则取行并从第二个列表中添加附加值?

musical_groups_Rock = [
    ["1", "Ad", "Rock", "1"],
    ["2", "John", "Lennon", "2"],
    ["3", "Rivers", "Cuomo", "3"],
    ["4", "Patrick", "Wilson", "4"],
]

musical_groups_Folk = [
    ["2", "John", "Lennon", "1"],
    ["1", "Ad", "Rock", "2"],
    ["5", "Axl", "Rose", "3"],
    ["7", "Jam", "Master", "4"],
]

def intersect(list_of_names1, list_of_names2):
    #Tried to join values first, but this way I could only compare ID + names.
    list1 = [" ".join(line[:-1]) for line in list_of_names1]
    list2 = [" ".join(line[:-1]) for line in list_of_names2]
    list3 = list(set(list1) & set(list2))
    return list3
    pass

output = intersect(musical_groups_Rock, musical_groups_Folk)
print(output[0:3])

你想要的输出并不完全清楚,但主要思想是制作一个以艺术家 ID 为键的字典,然后你可以映射任何你想要的信息:

d_folk = {l[0]: l[-1] for l in musical_groups_Folk}
out = [l+[d_folk.get(l[0], None)] for l in musical_groups_Rock]

输出:

[['1', 'Ad', 'Rock', '1', '2'],
 ['2', 'John', 'Lennon', '2', '1'],
 ['3', 'Rivers', 'Cuomo', '3', None],
 ['4', 'Patrick', 'Wilson', '4', None]]
只保留匹配的元素:
d_folk = {l[0]: l[-1] for l in musical_groups_Folk}
[l+[d_folk[l[0]]] for l in musical_groups_Rock if l[0] in d_folk]

输出:

[['1', 'Ad', 'Rock', '1', '2'],
 ['2', 'John', 'Lennon', '2', '1']]