混淆使用LPTHW ex 39的缩写

时间:2016-06-10 00:00:17

标签: python

以下是学习PYthon The Hard Way中此示例的代码:

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”声明? - 想想我现在明白这一点,但稍微澄清一下会很好。我是新手,只用于包含一个变量的for循环:

fruits = [apples, oranges, grapes]

for fruit in fruits:
  print "A fruit of type: %s" % fruit

最后,为什么措辞states.items()和cities.items()?为什么需要.items,不能只是state()和cities()吗?我刚刚意识到你需要.items,因为我们从dict调用了多个变量,而不只是一个。那是对的吗?在这样的情况下它会一直是.items吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

首先,avoid LPTHW

  

最后,为什么措辞states.items()和cities.items()?为什么需要.items,不能只是state()和cities()?

尝试运行print states.items()print states(),看看会发生什么。在问别人之前,你应该总是试验这些事情。

for state, abbrev in states.items():是:

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

这称为元组解包。