Jan*_*cka 1 python dictionary split strip
我最近问了一个关于将值列表从txt文件转换为字典列表的问题.你可以从这里的链接看到它:在这里查看我的问题
P883, Michael Smith, 1991
L672, Jane Collins, 1992
(added)
(empty line here)
L322, Randy Green, 1992
H732, Justin Wood, 1995(/added)
^key ^name ^year of birth
def load(filename): students = {}Run Code Online (Sandbox Code Playgroud)infile = open(filename) for line in infile: line = line.strip() parts = [p.strip() for p in line.split(",")] students[parts[0]] = (parts[1], parts[2]) return students
但是当txt文件的值中有一个行空间时(参见添加的部分)它不再起作用并且给出一个错误,说列表索引超出范围.
检查for循环中的空行并跳过它们:
for line in infile:
line = line.strip()
if not line:
continue
parts = [p.strip() for p in line.split(",")]
students[parts[0]] = (parts[1], parts[2])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11659 次 |
| 最近记录: |