我收到语法错误 |我正在向学习 Python The Hard Way 学习



这是我的代码,它与pdf的代码完全相同

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 abbreviation is: ", states["Michigan"]
print "Florida's abbreviation is: ", states["Florida"]
print "-" * 10
print "Michigan has: ", cities[states["Michigan"]]
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])
print "-" * 10
state = states.get("Texas", None)
if not state:
print "Sorry, no Texas."
city = cities.get("TX", "Does Not Exist")
print "The city for the state 'TX' is: %s" % city 

这是我的错误,我放入我的终端python ex39.py,我得到了这个。

File "ex39.py", line 3
"Oregon":"OR",
^
SyntaxError: invalid syntax

我运行的是 macOS 10.13.6 测试版 (17G47b( MacBook(13 英寸,2010 年中( 处理器 2.4 GHz 英特尔酷睿 2 双核处理器 内存 8 GB 1067 MHz DDR3 图形 英伟达 GeForce 320M 256 MB

所以这里的问题是当你使用括号 [] 时,它会创建一个列表,如 [1,2,3,4,5]。 虽然该列表中的 1-5 个都在同一个列表中,但它们并不直接相互交互。 您正在寻找使用大括号 {} 的字典。它需要一组信息,但它将它们成对地获取密钥及其值。

所以你需要这个

states = {
"Oregon":"OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
}
cities = {
"CA": "San Francisco",
"MI": "Detroit",
"FL": "Jacksonville"
}

货币对中的第一个是它们的关键,第二个是值。 希望这有帮助!祝您编码愉快!

最新更新