2011-03-29 92 views
1

我最近問了一個關於將值列表從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文件。(見增加的部分),它不工作了,並給了一個錯誤,指出列表索引超出範圍。

+1

要求檢查長度> 0的字符串或非空的檢查真的很差 - -1 – 2011-03-29 13:27:05

回答

6

檢查你的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]) 
+0

謝謝,它的效果很好 – Janezcka 2011-03-29 13:28:10

+0

如果行是0,該怎麼辦? – 2012-12-05 02:11:02

+0

@MarkLakewood我認爲這是假定行是一個字符串 – yuf 2013-07-16 21:59:30

0

通過計算parts的元素(如果parts中有零個元素(或通常少於三個元素),該行爲空或至少無效)檢查空行。或者通過檢查line針對空字符串的修整值。 (對不起,我不能Python的代碼,所以沒有代碼示例這裏...)

記住:你應該總是檢查動態創建陣列的索引之前的大小。

-1

這真是直截了當地檢查線路的emptyness或長度爲0:

for line in infile: 
    line = line.strip() 
    if line: 
     do_something() 

    # or 

    if len(line) > 0: 
     do_something() 
+0

即時通訊對不起,即時通訊初學者,仍然不知道大部分基本代碼 – Janezcka 2011-03-29 13:29:47

+1

http://diveintopython.org/ http://docs.python.org/tutorial/ – 2011-03-29 13:32:43

+0

如果行爲0會怎麼樣? – 2012-12-05 02:10:07

0
lines = [line.split(', ') for line in file if line] 
result = dict([(list[0], element_list[1:]) for line in lines if line]) 
相關問題