将函数转换为嵌套列表理解 (Python)

Convert function into a nested list comprehension (Python)

任何人都可以将以下函数转换为列表压缩!

 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

这是我能想到的最好的,但它是不正确的。

result = [user for user in users for contact in contacts if contact['username'] == user['username']]

感谢您的帮助。

因为 if i['username'] != result[len(result)-1]['username']: result.append(i) 真正做的是在 y 中没有任何东西匹配 iusername 时追加 i(因为如果 y 循环中有任何匹配,result 中的最后一项将具有与 i 相同的 username),您可以将内部循环设为子列表,并且如果子列表为空,则使用 or 运算符默认为 [i],最后使用嵌套列表理解来展平列表:

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]

或者如果您更喜欢后一个代码示例中的变量名称:

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]