【问题标题】:Python dictionary syntax, having a for conditionPython 字典语法,具有 for 条件
【发布时间】:2020-04-27 12:00:59
【问题描述】:

我有这本词典,

states = {
    'CT': 'Connecticut',
    'CA': 'California',
    'NY': 'New York',
    'NJ': 'New Jersey'
    }

和代码在这里..

state2 = {state: abbrev for abbrev, state in states.items()}

我试图了解abbrev for abbrev 的工作原理和方式。我也不清楚state: 到底是什么。我得到第二部分(states.items() 中的状态)。这个的输出给出了

{'Connecticut': 'CT', 'California': 'CA', 'New York': 'NY', 'New Jersey': 'NJ'}

但我不确定这是如何工作的。提前谢谢你。

【问题讨论】:

标签: python dictionary dictionary-comprehension iterable-unpacking


【解决方案1】:

字典推导类似于列表推导。 states.items() 是一个生成器,它将返回原始字典中每个项目的键和值。因此,如果您要声明一个空字典,遍历项目,然后翻转键和值,您将拥有一个新字典,它是原始字典的翻转版本。

state2 = {}
for abbrev, state in states.items():
    state2[state] = abbrev

从循环结构转换

翻转线条的顺序

state2 = {}
    state2[state] = abbrev
for abbrev, state in states.items():

扩展括号以包围所有内容

state2 = {
    state2[state] = abbrev
for abbrev, state in states.items():
}

修复分配,因为 state2 未分配

state2 = {
    state: abbrev
for abbrev, state in states.items():
}

放弃原来的:

state2 = {
    state: abbrev
for abbrev, state in states.items()
}

整理线条

state2 = {state: abbrev for abbrev, state in states.items()}

使用理解语法通常更快且更受欢迎。

【讨论】:

    【解决方案2】:

    这里发生的事情被称为字典理解,一旦你看过它们就很容易阅读。

    state2 = {state: abbrev for abbrev, state in states.items()}
    

    如果您查看state: abbrev,您可以立即看出这是一个常规的对象分配语法。您将 abbrev 的值分配给状态键。但是什么是状态和缩写?

    您只需要查看下一条语句,for abbrev, state in states.items()

    这里有一个 for 循环,其中 abbrev 是键,state 是项目,因为 states.items() 返回一个键和值对。

    所以看起来字典推导正在为我们创建一个对象,通过循环一个对象并在它循环时分配键和值。

    【讨论】:

    • 添加一点上下文,这与dict(map(reversed, states.items())) 相同并与this Q&A 相关
    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2017-09-11
    • 2015-10-24
    相关资源
    最近更新 更多