Can anyone convert the below function into a list compressions please!
def something(x,y):
result = []
for i in x:
for j in y:
if i['username'] == j['username']:
result.append(j)
if i['username'] != result[len(result)-1]['username']:
result.append(i)
return result
This is best I could come up with but it is not correct.
result = [user for user in users for contact in contacts if contact['username'] == user['username']]
Thank you for any help.
Since what if i['username'] != result[len(result)-1]['username']: result.append(i)
is really doing is to append i
when there is nothing in y
found to match the username
of i
(because if there was any match in the y
loop the last item in result
would have the same username
as i
), you can make the inner loop a sub-list and use the or
operator to default to [i]
if the sub-list is empty, and finally use nested list comprehension to flatten the list:
result = [a for s in [[j for j in y if i['username'] == j['username']] or [i] for i in x] for a in s]
Or if you prefer the variable names in your latter code example:
result = [a for s in [[contact for contact in contacts if user['username'] == contact['username']] or [user] for user in users] for a in s]