如何检查字符串是否为空或长度z

2024-04-20 00:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近问了一个关于将值列表从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 


但是,当txt文件的值中有一个行空间时。。(参见添加的部分)它不再工作,并给出一个错误,说明列表索引超出范围。

Tags: 文件intxt列表addedfor字典here
3条回答
lines = [line.split(', ') for line in file if line]
result = dict([(list[0], element_list[1:]) for line in lines if line])

检查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])

通过计算parts中的元素(如果parts中有零个(或通常少于三个)元素,则该行为空或至少无效)。或者根据空字符串检查line的修剪值。(抱歉,我无法编写Python代码,因此此处没有代码示例…)

记住:在索引动态创建的数组之前,应该检查它的大小。

相关问题 更多 >