在 f 字符串中使用理解式

问题描述 投票:0回答:1

我正在尝试从字典中选择键并将它们插入到使用此代码的 f 字符串中,这会导致交互式解释器中出现以下错误:

    f'{a for a in f.__dict__.keys() if a.isupper()}'
         ^^^
SyntaxError: f-string: expecting '=', or '!', or ':', or '}'

我尝试使用大写键打印消息但失败。我应该做什么?

python dictionary-comprehension
1个回答
-1
投票
f'[a for a in f.__dict__.keys() if a.isupper()]'

您需要列表理解,而不是字典理解。您正在迭代键列表。该错误是因为

{}
意味着理解需要键值格式的所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.