Reputation: 23
There are 2 lists. You need to combine these list items into one. So that the elements of the first match the values of the second and vice versa, the second=the first. But there is one thing, if there is an element in the second list that contains an underscore at the end, then you need to consider it correct and save the choice from the first list (without the underscore).
lst1 = ['NAME', 'SURNAME', 'AGE', 'ID']
lst2 = [['NAME', 'JOHN'], ['SURNAME', 'SMITH'], ['ACTIVE', 'Y'], ['ID_', '33']]
It should turn out like this
lst3 = [['NAME', 'JOHN'], ['SURNAME', 'SMITH'], ['ID', '33']]
I wrote such a variant, but it collects a complete match, which excludes elements with underscores. Is there any simple option not to exclude such elements when filtering.
lst3= sorted(filter(lambda x: x[0] in lst1, lst2),
key=lambda x: lst1.index(x[0]))
Upvotes: 1
Views: 384
Reputation: 11
lst1 = ['NAME', 'SURNAME', 'AGE', 'ID']
lst2 = [['NAME', 'JOHN'], ['SURNAME', 'SMITH'], ['ACTIVE', 'Y'], ['ID_', '33']]
lst3 = []
for i in lst1:
for j in lst2:
if i == j[0] or i + '_' == j[0]:
lst3.append(j)
print(lst3)
Upvotes: 1
Reputation: 195418
You can create a temporary dictionary for mapping:
lst1 = ["NAME", "SURNAME", "AGE", "ID"]
lst2 = [["NAME", "JOHN"], ["SURNAME", "SMITH"], ["ACTIVE", "Y"], ["ID_", "33"]]
tmp = {k.rstrip("_"): v for k, v in lst2}
out = [[k, tmp[k]] for k in lst1 if k in tmp]
print(out)
Prints:
[['NAME', 'JOHN'], ['SURNAME', 'SMITH'], ['ID', '33']]
Upvotes: 4