Python LPTHW ex 39缩略语使用混乱

Python LPTHW ex 39缩略语使用混乱,python,Python,以下是“艰苦学习PYthon”中此示例的代码: states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } cities['NY'] = 'New York' cities['OR'] = 'Portlan

以下是“艰苦学习PYthon”中此示例的代码:

states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}

cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

print '_' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']

print '_' * 10 
print "Michigan's abbreviations is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']

print '_' * 10
print "Michigan has: ", cities[states['Michigan']] #could do cities['MI']
print "Florida has: ", cities[states['Florida']]

print '_' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" %(state, abbrev)

print '_' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)

print '_' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" %(state, abbrev, cities[abbrev])

我对这四段代码中的“abbrev”一词感到困惑:

print '_' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" %(state, abbrev)

print '_' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)

print '_' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" %(state, abbrev, cities[abbrev])
我对最后一行中提到的城市特别困惑

谁能告诉我他是如何/为什么使用“for abbrev”语句的我想我现在明白了,不过稍微澄清一下就好了。我不熟悉这一点,只习惯于包含一个变量的循环,如:

fruits = [apples, oranges, grapes]

for fruit in fruits:
  print "A fruit of type: %s" % fruit
最后,为什么要用states.items()和cities.items()来表达呢?为什么需要.items,难道不能是states()和cities()吗?我刚刚意识到您需要.items,因为我们正在从dict调用多个变量,而不仅仅是一个。对吗?像这样的箱子里的东西会一直是吗

提前谢谢

首先

最后,为什么要用states.items()和cities.items()来表达呢?为什么需要.items,难道不能是states()和cities()吗

试着运行
print states.items()
print states()
看看会发生什么。在向别人询问这些事情之前,你应该先尝试一下

表示州,缩写为states.items():
是以下的缩写:

for item in states.items():
    state, abbrev = item  # which means state = item[0], abbrev = item[1]

这叫做元组解包。

谢谢Alex。我确实单独运行了它们,但在发布后愚蠢地这样做了——我编辑了这篇文章以反映这一点。至于避免LPTHW,我必须从某个地方开始,这实际上教会了我很多。接下来我将考虑Python。@Wolverine states.items()返回键和值对,states()是一个错误,直接在状态上迭代只会产生键。