2015-12-21 37 views
0
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!

+1

如果您的第一個循環覆蓋了'states'名稱。 –

回答

2

當您在第一個循環中將states指定爲目標時,將states的名稱重新指定給states.items()元組的第一項。

這裏是你在做什麼的簡化版本:

>>> i = "hello" 
>>> for i in range(2): print i 
... 
0 
1 
>>> i 
1 

正如你看到的,i是循環後int,而不是一個str,該值是指已經改變


作爲解決方案只需在循環中states重命名爲別的東西,像statetmp_states。所以:

for state, abbrev in states.items(): 
    print '%s is abbreviated as %s' % (state, abbrev) 

另外做在同樣的模式存在其他循環一樣,像for abbrev, cities in cities.items(): - >for abbrev, city in cities.items()

+0

相同的'城市' –

1

for states, abbrev in states.items(): 
    print('%s is abbreviated as %s' % (states, abbrev)) 

引起的麻煩。

由於python中循環變量的範圍不限於循環(可以說,它們'泄漏'到您的程序中),因此states將是一個字符串。

您可以通過運行

print(states) 
for states, abbrev in states.items(): 
    print('%s is abbreviated as %s' % (states, abbrev)) 
print(states) 

調試這將打印

---------- 
{'California': 'CA', 'Michigan': 'MI', 'New York': 'NY', 'Florida': 'FL', 'Oregon': 'OR'} 
California is abbreviated as CA 
Michigan is abbreviated as MI 
New York is abbreviated as NY 
Florida is abbreviated as FL 
Oregon is abbreviated as OR 
Oregon 

此外,你應該檢查你的print使用。請堅持印刷說明的一種版本,要麼print 'foo'print('foo')。第二個用法(作爲函數)是唯一能在Python 3.X中工作的用法。

+0

在這方面,我發現某些字符串+變量的printring有一個尷尬的結果,如果我打印功能。通常我使用打印功能,主要是爲了一致性 –

1

「城市」和「州」在第一個和第二個循環中被覆蓋。使用不同的變量名應該修復它。

相關問題