2012-11-16 78 views
0

我需要創建一個python函數,該函數從名爲「food.txt」的文件中讀取和列出雜貨,以便在找到文本文件中的新行時,通用列表中的新列表分組爲創建。列表的有序列表

food.txt:

milk 
cheese 
bread 

steak 
chicken 
potatoes 

^每個詞應該是對自己符合羣體

輸出之間的一個新行:[ '牛奶', '奶酪','麪包'],[' 牛排」, '雞', '土豆']

到目前爲止,我有:

def build_grocery_list(file_name): 
     outer_list=[] 
     inner_list=[] 

     food_list=open(file_name,"r") 
     for line in food_list: 
      line.strip('\n') # no white spaces in the list 

回答

0

試試這個(這裏是一個gist):

list_of_lists=[] 
category=0 
list_of_lists.append([]) 

f = open(file_name,'r') 

for line in f.readlines(): 
    item = line.strip('\n') # no white spaces in the list 
    if len(item) > 0: 
     #add to current category 
     list_of_lists[category].append(item) 
    else: 
     #add new category 
     list_of_lists.append([]) 
     category = category + 1 
f.close() 
+0

非常感謝你jason :) – pythonnoob

0

這是一個好的開始!您可以檢查您正在閱讀的行是否不爲空(len(line.strip('\n')) > 0)如果不是,則將行內容追加到inner_list(如果它爲空),請將完整的inner_list附加到outer_list並從新的inner_list開始。