def printdash():
print('-' * 10)
# creates a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# creates a basic set of states with some cities in them
cities = {
'CA': 'Sacramento',
'MI': 'Lansing',
'FL': 'Tallahasee'}
# add some more cities to the list
cities['NY'] = 'Albany'
cities['OR'] = 'Eugene'
# Print out some cities
printdash()
print('New York State has: ', cities['NY'])
print('Oregon has: ', cities['OR'])
# print some states
printdash()
print 'Michigan\'s abbreviation is: ' , states['Michigan']
print 'Florida\'s abbreviation is: ', states['Florida']
# do it by using the state then cities dict. Nested dicts!
printdash()
print 'Michigan has: ', cities[states['Michigan']]
print 'Florifa has: ', cities[states['Florida']]
# print every states abbreviation
printdash()
for states, abbrev in states.items():
print '%s is abbreviated as %s' % (states, abbrev)
# end
# print every city in each state
printdash()
for abbrev, cities in cities.items():
print '%s has the city %s' % (abbrev, cities)
# end
# doing both at the same time
printdash()
for state, abbrev in states.items():
print '%s state is abbreviated %s and has city %s' % (state, abbrev, cities[abbrev])
每次我運行它,它都會到第54行(最後一個循環),然後引發屬性錯誤標誌。對於我的生活,我無法弄清楚我在做什麼錯誤,因爲其他兩個循環,大多在同一時尚工作設置沒有問題。AttributeError:'str'對象沒有屬性'items'循環時出錯
查看本網站上的其他解決方案,我發現過去的示例比我能理解的更復雜一些,解決方案似乎比這個非常普遍的案例更具體一些。
Shanks!
如果您的第一個循環覆蓋了'states'名稱。 –