2015-11-02 43 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()) 

你会得到你通缉。