一行条件赋值 if 语句

One line conditional assignment if statement

这是我在这个论坛上提出的第一个问题,所以我欢迎您提供反馈,让这个问题对其他人更有帮助。

假设我有这个列表:

IDs = ['First', 'Second', 'Third']

和这本词典:

statistics = {('First', 'Name'):"FirstName", ('Second','Name'):"SecondName", ('Third','Name'):"ThirdName"}

是否有比以下更短、更容易阅读的单行代码?

firstID = IDs[[statistics[ID,'Name'] for ID in IDs].index('FirstName')]

非常感谢

一个更有效(并且可能更易读)的方法是这样的:

firstID = next(id for id in IDs if statistics[(id,'Name')]=='FirstName')

这定义了一个 generator which checks the IDs in order, and yields values from statistics that equal "FirstName". next(...) 用于从此迭代器中检索第一个值。如果没有找到匹配的名称,这将引发 StopIteration.

# If you ever plan to change the order of IDs:
firstID = IDs[IDs.index('First')]

# If you are literally just looking for the first ID in IDs:
firstID = IDs[0]

如果您查看这两行代码:

IDs = ['First', 'Second', 'Third']
firstID = IDs[[statistics[ID,'Name'] for ID in IDs].index('FirstName')]

您新创建的列表中 'FirstName' 的索引将始终等于 IDs'First' 的索引。因为您的列表理解将按顺序迭代 IDs 并将相应的 dict 值按该顺序放置,所以您将始终在与 'First' 出现在 [=] 相同的索引处创建 'FirstName' 14=]。因此,使用上述方法之一从该列表中简单地调用它会更有效。