【问题标题】:Python, list comprehension, filter single element in the list [duplicate]Python,列表理解,过滤列表中的单个元素[重复]
【发布时间】:2020-02-11 07:26:48
【问题描述】:

很多时候,在 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

有没有更优雅的 Pythonic 方式将最后两行放入其中?

【问题讨论】:

  • filter 有什么问题?
  • 不建立列表; next(<generator expression>, None).
  • 我建议你使用类。首先需要做更多的工作,但会在扩展代码时为您节省大量时间。

标签: python list-comprehension


【解决方案1】:

使用next:

admin = next((x for x in users if x['role'] == 'admin'), None)
print(admin)

输出

{'email': 'admin@example.io', 'role': 'admin'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 2017-11-28
    • 2021-12-20
    • 2015-12-13
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多