2016-12-08 41 views
0

我想弄清楚如何從文件中獲取元素到3D列表中。如何將文件中的元素放入3D列表中? Python

例如,如果我的people.txt文件看起來像:

3 4 

SallyLee 
MallieKim 
KateBrown 
JohnDoe 
TreyGreen 
SarahKind 

但我只想SallyLee等,在沒有頂部號碼3D名單。

到目前爲止,我已經編碼:

def main(): 
    list = [] 


    peopleFile = open("people.txt") 
    peopleRead = peopleFile.readlines() 

    for lines in peopleRead: 
     list.append([lines]) 

    peopleFile.close() 
    print(list) 
main() 

這然後打印與數字,而不是在3D名單。

的什麼,我試圖做一個例子是:

[[[SallyLee],[MallieKim],[KateBrown]],[[JohnDoe],[TreyGreen],[SarahKind]]] 

,每一個第三人「組合」在一起。

我不期待任何人爲我編寫任何代碼!

我只希望有人能帶領我走向正確的方向。

謝謝

回答

0

首先,如果你正在尋找的是一個字符串(而非數字),你就可以開始你的for循環斷了條件,通過有數字的任何元素。你可以用try:/except:來做到這一點。 接下來,您可以使用範圍函數的參數來製作您感興趣的索引列表。如果您想按三分組分組,則可以讓range列出三個的倍數(0,3 ,6,9,...)

這裏是我的代碼:

file = open('text.txt','r') 

i = 0 
names = [] 
for line in file: 
    line.split() #This will split each line into a list 
    try: #This will try to convert the first element of that list into an integer 
     if int(line[0]): #If it fails it will go to the next line 
      continue 
    except: 
     if not line.strip(): #This will skip empty lines 
      continue 
     names.append(line.strip()) #First let's put all of the names into a list 


names = [names[i:i+3] for i in range(0,len(names)-1,3)] 
print names 

輸出:

[['SallyLee', 'MallieKim', 'KateBrown'], ['JohnDoe', 'TreyGreen', 'SarahKind']] 
相關問題