有没有人可以把下面的函数转换成一个列表压缩!
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']]
谢谢你的帮助。
发布于 2018-07-27 07:24:39
由于if i['username'] != result[len(result)-1]['username']: result.append(i)
真正做的是在y
中找不到匹配i
的username
时附加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]
https://stackoverflow.com/questions/51548633
复制相似问题