我是Python初学者。在苦练了《学Python》的ex39后,我试着用字典来写我的家乡城市。在
以下是我写的:
states = {
'Orangon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
}
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
print states.get('Florida')
print states.get('California')
cities = {
'New Taipei': 'NTP',
'Taipei': 'TP',
'Kaohsiung': 'KHU',
'Taichung': 'TAC',
'Taoyuan': 'TYN',
'Tainan': 'TNA',
'Hsinchu': 'HSC',
'Keelung': 'KLG',
'Chiayi': 'CYI',
'Changhua': 'CHA',
'Pingtung': 'PTG',
'Zhubei': 'ZBI',
'Yuanlin': 'Yln',
'Douliu': 'Dlu',
'Taitung': 'TAT',
'Hualien': 'HUl',
'Toufen': 'TFE',
'Yilan': 'Yln',
'Miaoli': 'Mli',
'Magong': 'Mgn',
}
for cities, abbrev in cities.items():
print "%s is %s" % (cities, abbrev)
print cities.get('Magong')
最后一个代码有错误:
回溯(最近一次呼叫): 文件“ex39.2.py”,第27行,in 打印城市。获取(“马公”) AttributeError:“str”对象没有属性“get”
我不明白为什么print states.get('California')
中没有错误,print cities.get('Magong')
中却有错误
在for循环中,为变量
cities
分配一个字符串:因此,在for循环之后,
cities
不再是dict,而是一个字符串。在解决方案:在循环中使用其他变量:
^{pr2}$相关问题 更多 >
编程相关推荐