我最近问了一个关于将值列表从txt文件转换为字典列表的问题。您可以在此处的链接中看到它:See my question here
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 = {}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
答案 0 :(得分:7)
检查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])
答案 1 :(得分:0)
通过计算parts
的元素来检查空行(如果parts
中有零(或通常少于三个)元素,则该行为空或至少无效)。或者通过检查line
对空字符串的修剪值。 (对不起,我不能编写Python代码,所以这里没有代码示例......)
请记住:在索引之前,您应该始终检查动态创建的数组的大小。
答案 2 :(得分:0)
lines = [line.split(', ') for line in file if line]
result = dict([(list[0], element_list[1:]) for line in lines if line])
答案 3 :(得分:-1)
检查线条的空白或长度0非常简单:
for line in infile:
line = line.strip()
if line:
do_something()
# or
if len(line) > 0:
do_something()