2015-11-02 40 views
-2
列表

有一個代碼:拆分內部的Python

def readData(): 
    file = open('data.txt', 'r') 
    listing = [] 
    for line in file: 
     print(line.split()) 
     depart = line.split() 
     m = [line.strip()] 
     listing.append(m) 

    file.close() 
    return listing 

def display(): 
    depart = readData() 
    poorest = [] 
    if int(depart[1]) <= int(depart[2])+int(depart[3]): 
     poorest.append(depart[0]) 
    print(poorest) 

的 '離開' 輸出會產生這樣的:

[['Ladies 250 184 196'], ['Gentlemen 167 321 459'], ['Toys \t180 150 210'], ['Beauty\t450 280 320'], ['Technology\t169 320 279'], ['Home\t120 58 45'], ['Appliances\t210 130 67'], ['Food\t180 45 89'], ['Shoes\t260 100 210'], ['Children 179 50 80']] 

但我需要產生這樣的:

['Ladies', '250', '184, '196'] 

每一個。我應該如何改變第二個功能?

+2

試試這個,而不是'poorest.append(depart [0] .split())'在這裏你分裂給定的字符串在空間 – The6thSense

回答

1

或者更pythonic

def ReadData(): 
    file = open('data.txt', 'r') 
    listing = [[part.strip() for part in line.split()] for line in file] 
    file.close() 
    return listing 

閱讀List Comprehensions

接下來,我們需要str轉換爲int

[[part.strip() if idx == 0 else int(part.strip()) 
    for idx, part in enumerate(line.split())] 
for line in file] 

現在我們有名單:

[['Ladies', 250, 184, 196], ['Gentlemen', 167, 321, 459], ... 
+0

它的工作原理,謝謝! 還有一個問題:如何比較這些嵌套列表中的數字?如果你能幫助我,我將非常感激。我試圖自己做這件事,但我失敗了。 –

0

你不追加分裂名單列表中,你最終返回,因此,如果您更改下面

depart = line.split() 
m = [line.strip()] 
listing.append(m) 

的線

listing.append(line.strip().split()) 

你會得到你通緝。