很多時(shí)候,在 Python 中編程時(shí),我需要過濾列表中的單個(gè)元素。為此,我使用以下代碼模式: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有沒有更優(yōu)雅的 Pythonic 方式將最后兩行放入其中?
Python,列表理解,過濾列表中的單個(gè)元素
慕蓋茨4494581
2022-06-22 17:28:15
