【问题标题】:Is there a way to condense this into a dictionary comprehension?有没有办法把它浓缩成字典理解?
【发布时间】:2021-02-16 07:19:43
【问题描述】:

我正在尝试将其浓缩,但在遍历列表时尝试在理解中实现正则表达式时陷入困境。

acl_lines = some_list
hash_dict = {}
for line in acl_lines:
    search = re.search(hash_regex, line)
    if search:
        hash_dict[search.group(2)] = search.group(1)

【问题讨论】:

标签: python dictionary dictionary-comprehension


【解决方案1】:

您可以执行以下操作:

hash_dict = {
    s.group(2): s.group(1) 
    for s in (re.search(hash_regex, line) for line in acl_lines) if s
}

为了不调用两次search,您插入了一个额外的生成器表达式。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2012-09-26
    • 2019-09-15
    • 2019-07-31
    • 1970-01-01
    • 2010-11-20
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多