我收到一个SyntaxError |我正在从学习Python的艰难道路中学习

时间:2018-06-26 17:34:25

标签: python-2.7

这是我的代码,与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 Beta(17G47b) MacBook(13吋,2010年中) 处理器2.4 GHz Intel Core 2 Duo 内存8 GB 1067 MHz DDR3 图形NVIDIA GeForce 320M 256 MB

1 个答案:

答案 0 :(得分:0)

所以这里的问题是,当您使用方括号[]时,它会列出一个列表,例如[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"
}

这对中的第一个是键,第二个是值。 希望这可以帮助!编码愉快!