很多時候,在 Python 中編程時,我需要過濾列表中的單個元素。為此,我使用以下代碼模式:user1 = {'email': '[email protected]', 'role': 'admin'}user2 = {'email': '[email protected]', 'role': 'user'}user3 = {'email': '[email protected]', 'role': 'user'}users = [user1, user2, user3]temp = [x for x in users if x['role'] == 'admin']admin = temp[0] if temp else None有沒有更優雅的 Pythonic 方式將最后兩行放入其中?
Python,列表理解,過濾列表中的單個元素
慕蓋茨4494581
2022-06-22 17:28:15