Trying to find the way how to intersect 2 lists by "first argument" = musician's ID. As output we need to get ID / Name / Lastname / Rating's place in first list / Rating's place in second list
Example:
["1", "Ad", "Rock", "1", "2"], ["2", "John", "Lennon", "2", "1"]
Is there better way how to compare lists by ID, and if it is TRUE, then take line and add additional value from second list?
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])
CodePudding user response:
The output you want is not fully clear, but the main idea is to craft a dictionary with the artist ID as key, then you can map any info you want:
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]
output:
[['1', 'Ad', 'Rock', '1', '2'],
['2', 'John', 'Lennon', '2', '1'],
['3', 'Rivers', 'Cuomo', '3', None],
['4', 'Patrick', 'Wilson', '4', None]]
keeping only the elements that have a match:
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]
output:
[['1', 'Ad', 'Rock', '1', '2'],
['2', 'John', 'Lennon', '2', '1']]