通常,在用Python编程时,我需要过滤列表中的单个元素。
为此,我使用以下代码模式:
user1 = {'email': 'admin@example.io', 'role': 'admin'}
user2 = {'email': 'xuser@example.io', 'role': 'user'}
user3 = {'email': 'yuser@example.io', 'role': 'user'}
users = [user1, user2, user3]
temp = [x for x in users if x['role'] == 'admin']
admin = temp[0] if temp else None是否有更优雅的毕达通方式来将最后两条线插入其中?
发布于 2019-10-14 16:29:54
使用下一首
admin = next((x for x in users if x['role'] == 'admin'), None)
print(admin)输出
{'email': 'admin@example.io', 'role': 'admin'}https://stackoverflow.com/questions/58380706
复制相似问题