python - How to put certain instances of a text file to a list in python
问题描述
This is what a part of the txt file looks like:
3/Kingsbury Dr/Waterdale Rd/Bundoora
4/Crissane Rd/Waterdale Rd/Heidelberg West
I just want to get the second element which is the bus stop (eg Kingsbury Dr, Crissane Rd) instance in a list. Here is what I have tried so far and not sure how to put the second element in a list
def loadData():
with open('BusRoute250.txt', 'r') as f:
busStopList = []
f_line = f.readline()
while f_line:
file_line_lst = list(f_line.strip().split('/'))
f_line = f.readline()
for f_line in file_line_lst:
busStopList.append()
print(busStopList)
The link for txt file contents: https://docs.google.com/document/d/1ah1EAhro_5-pgqIDylFSjTyHI9fvylfErB8pFNZb36A/edit?usp=sharing
解决方案
You need to add the second element of the list formed in the result of split('/')
operation.
busStopList.append(file_line_lst[1])
The while
loop is a bit wrong. It should be like this:
while f_line:
file_line_lst = list(f_line.strip().split('/'))
busStopList.append(file_line_lst[1])
f_line = f.readline()
推荐阅读
- python-3.x - Python3 tkinter - 带有类的新窗口为空白+原始窗口中的新窗口内容
- json - 在 Swift 上访问变量 do-catch 语句
- php - php 文件中未捕获的异常“PDOException”
- excel - Excel:如果单元格1为空,则在单元格2中显示“NA”,否则显示带有一些选项的下拉列表
- java - 从 Spring 3.2 迁移到 Spring 4.3
- matplotlib - Matplotlib 旋转 3d 对象
- python - 如果从未在测试中直接调用函数,是否可以制作 pytest 报告?
- apache-kafka - Kafka + Spring Batch Listener Flush Batch
- powershell - 以登录用户身份运行 powershell 脚本
- ios - Issue in updating value from `UserDefaults` in Swift