2 回答
TA贡献1827条经验 获得超9个赞
你正在寻找的是这样的东西。考虑一次遍历一行的循环,并为您的条件构建一系列检查。附注。如果这不起作用,请告诉我,未经测试就编写它。
State_Dict = {}
with open('state.txt', 'r') as main_fd:
for line in main_fd:
line = line.strip() #left and right stripped
#if ("state" in line.lower()): #better version suggested in comments to handle 'state' and 'State'.
if ("State" in line):
state_key = "_".join(line.split()[1:])
State_Dict[state_key] = []
elif ("!" in line):
continue #goes to next iteration of loop instead of stopping the loop unlike break
else: #assuming last case
State_Dict[state_key].append(line) #line has already been stripped
print(State_Dict)
TA贡献1934条经验 获得超2个赞
你的代码的问题是当你出现“!”时,你正在停止寻找一个州的城市。但城市的新部分也由以“State”开头的线表示。另一个错误是您每次都从头开始迭代城市,而不是您当前所处的状态。
State_Dict = {}
main_fd = '''\
State Texas
Austin
Houston
Dallas
State Florida
Orlando
Miami
Jacksonville
Naples
!
State California
San Diego
Los Angeles
San Francisco\
'''.splitlines()
for idx, mystate in enumerate(main_fd):
if "State" in mystate:
state_key = "_".join(mystate.split()[1:])
State_Dict[state_key] = []
for cities in main_fd[idx+1:]:
if '!' in cities or "State" in cities:
break
else:
State_Dict[state_key].append(cities.rstrip())
print(State_Dict)
输出:
{'Florida': ['Orlando', 'Miami', 'Jacksonville', 'Naples'],
'California': ['San Diego', 'Los Angeles', 'San Francisco'],
'Texas': ['Austin', 'Houston', 'Dallas']}
添加回答
举报