【问题标题】:Walrus operator in dict declarationdict 声明中的海象运算符
【发布时间】:2022-07-01 21:51:36
【问题描述】:

我想在字典声明中使用海象运算符。但是: 可能会导致问题。我有一个嵌套在列表理解中的字典声明,但我不想将它分解为一个简单的 for 循环(这将是一个懒惰的答案)。有没有可能?

rows = [
    {
        'words': sorted(row_words, key=lambda x: x['x0']),
        'top': top := min(map(lambda x: x['top'], row_words)),
        'doctop': top + doctop_adj,
    } for row_words in doctop_clusters
]

这在一些简单的场景中也很有用。

foo = {
    'a': a := some_calculation(),
    'b': a * 8
}

注意: walrus operator in dict comprehension 没有回答我的问题,因为我没有可以使用海象运算符的条件。而且下面的做法很不干净。

rows = [
    {
        'words': sorted(row_words, key=lambda x: x['x0']),
        'top': top,
        'doctop': top + doctop_adj,
    } for row_words in doctop_clusters 
    if top := min(map(lambda x: x['top'], row_words)) or True
]

【问题讨论】:

  • 您需要将它包含在括号中,就像您链接到的问题一样 - 'a': (a := some_calculation()),

标签: python dictionary list-comprehension walrus-operator


【解决方案1】:

以下是在您的案例中如何使用海象运算符:

rows = [
    {
        'words': sorted(row_words, key=lambda x: x['x0']),
        'top': (top := min(map(lambda x: x['top'], row_words))),
        'doctop': top + doctop_adj,
    } for row_words in doctop_clusters
]

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2020-11-17
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2021-12-07
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多