如何将提取的车站与位置列表转换为指定格式字符串并换行打印
问题解决:车站与位置信息格式化输出
原文本数据
text_file = "London Euston 12 London 56, Aylesbury Vale 87 Parkway 99, James Cook 76 University 87, Virginia Water 42 Surrey 78"
期望输出
Stations: London Euston Aylesbury Vale James Cook Virginia Water Locations: 12 London 56 87 Parkway 99 76 University 87 42 Surrey 78
当前代码(存在两处问题)
replaced = text_file.replace(","," ") replaced_split = replaced.split() i = 0 b = 2 stations = [] locations = [] while b < len(replaced_split): locations.append(replaced_split[b:b+3]) b += 5 while i < len(replaced_split): stations.append(replaced_split[i:i+2]) i += 5 for x in range(len(stations)): print(stations[x]) for y in range(len(locations)): print(dates[y])
当前错误输出
['London', 'Euston'] ['Aylesbury', 'Vale'] ['James', 'Cook'] ['Virginia', 'Water'] ['12', 'London', '56'] ['87', 'Parkway', '99'] ['76', 'University', '87'] ['42', 'Surrey', '78']
修正方案
直接修改现有代码,解决核心问题:
- 用
' '.join()方法将子列表元素拼接成字符串,避免输出列表对象格式 - 修正变量名错误,把
dates[y]改为locations[y] - 添加要求的标题和分隔空行,匹配期望输出格式
修正后的代码:
text_file = "London Euston 12 London 56, Aylesbury Vale 87 Parkway 99, James Cook 76 University 87, Virginia Water 42 Surrey 78" replaced = text_file.replace(","," ") replaced_split = replaced.split() i = 0 b = 2 stations = [] locations = [] while b < len(replaced_split): # 直接拼接成字符串存入列表 locations.append(' '.join(replaced_split[b:b+3])) b += 5 while i < len(replaced_split): # 直接拼接成字符串存入列表 stations.append(' '.join(replaced_split[i:i+2])) i += 5 # 按要求格式输出 print("Stations:") for station in stations: print(station) # 空行分隔 print() print("Locations:") for location in locations: print(location)
运行这段代码即可得到符合要求的输出结果。
内容的提问来源于stack exchange,提问作者Still Learning
相关产品推荐
相关产品推荐

