窝在家里写程序 发表于 2020-10-24 16:49:23

求大神解答

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 Steat has:',cities['NY'])
print('OR Steat has:',cities['OR'])


print('-' * 10)
print("Michigan's abbreviation is:",states['Michigan'])
print("Florida's abbreviation is:",states['Florida'])


print('-' * 10)
print("Michigan has:",cities])
print("Florida has:",cities])


print('-' * 10)
for state, abbrev in list(states.items()):
    print(f"{abbrev} has the city {abbrev}")


print('-' * 10)
for abbrev,city in list(cities.items()):
    print(f'{abbrev} has the city {city}')


print('-' *10)
for state, abbrev in list(states.items()):
    print(f'{state} state is abbreviated {abbrev}')
    print(f"and has city {cities}")

print('-' * 10)

state = state.get('Texas')

if not state:
    print("Sorry, no Texas.")


city = cities.get('TX','Does Not Exist')
print(f'The city for the state "TX" is:{city}')





我想问下   我哪里出错了出什么错了

冰河星云 发表于 2020-10-24 17:47:35

本帖最后由 冰河星云 于 2020-10-25 15:49 编辑

拼写错误吧
而且字符串里没有get这个方法
改成
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 Steat has:',cities['NY'])
print('OR Steat has:',cities['OR'])


print('-' * 10)
print("Michigan's abbreviation is:",states['Michigan'])
print("Florida's abbreviation is:",states['Florida'])


print('-' * 10)
print("Michigan has:",cities])
print("Florida has:",cities])


print('-' * 10)
for state, abbrev in list(states.items()):
    print(f"{abbrev} has the city {abbrev}")


print('-' * 10)
for abbrev,city in list(cities.items()):
    print(f'{abbrev} has the city {city}')


print('-' *10)
for state, abbrev in list(states.items()):
    print(f'{state} state is abbreviated {abbrev}')
    print(f"and has city {cities}")

print('-' * 10)

if 'Texas' not in state:
    print("Sorry, no Texas.")


city = cities.get('TX','Does Not Exist')
print(f'The city for the state "TX" is:{city}')

altf11 发表于 2020-10-24 18:15:32

楼上的代码有行号,参照楼上的代码说(以后发帖子最好使用高级模式里的代码编辑器,<>这个符号,代码发出来有行号,好说明)

首选,第32、33行,使用字典 states 的 value 作为字典 cities 的键取值,但大小写不对应,改成对应的

这点楼上说过了,第03行Fl 改成FL,第 04行Ca 改成CA

其次第60行, 第 47行 for state, abbrev in list(states.items()) 解包后 state为字符串类型

字符串是没有 .get() 这个方法的,你可以将 第53 到第 56行改成:

if 'Texas' not in state:
    print("Sorry, no Texas.")
页: [1]
查看完整版本: 求大神解答