Python字典语法,具有for条件

问题描述 投票:2回答:2

我有这本字典,

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
2个回答
5
投票

这里发生的事情称为字典理解,一旦您足够了解它们,就很容易阅读。

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

如果查看state: abbrev,您可以立即知道这是一个常规对象分配语法。您正在将abbrev的值分配给状态键。但是状态是什么,简称?

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

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

所以看起来字典理解是通过遍历一个对象并在其循环时分配键和值来为我们创建一个对象。


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()}

使用理解语法通常更快,更可取。

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