2016-11-06 118 views
2

基本上我試圖做的是將每行中的每個字符讀入列表中,並在每行之後添加該列表到另一個列表(輸入文件每行一個列表,每個列表包含每行的所有單個字符)將每行輸入文件中的每個字符添加到列表中,並在每行之後將每個列表添加到另一個列表中

這是我迄今爲止,但它似乎並沒有工作,我不知道爲什麼。

allseq = [] 
with open("input.txt", "r") as ins: 
    seq = [] 
    for line in ins: 
     for ch in line: 
      if ins != "\n": 
       seq.append(ch) 
      else: 
       allseq.append(seq) 
       seq[:] = [] 

print(allseq) 

回答

2

Python中的字符串可以很容易地轉換成文字列表!讓我們來做一個功能。

def get_char_lists(file): 
    with open(file) as f: 
     return [list(line.strip()) for line in f.readlines()] 

這將打開一個文件進行讀取,讀取所有的線,剝去多餘的空白,粘字符列表到一個列表,並返回最後一個列表。

+0

謝謝!這是一個更優雅的解決方案。 – Matt

+0

@Matt,沒問題!要開始某處! :) –

1

即使有更簡單的方法(@Pierce答案),您的原始代碼有兩個問題。第二點很重要。

allseq = [] 
with open("input.txt", "r") as ins: 
    seq = [] 
    for line in ins: 
     for ch in line: 
      if ch != "\n":   # Use ch instead of ins here. 
       seq.append(ch) 
      else: 
       allseq.append(seq) 
       seq = []   # Don't clear the existing list, start a new one. 

print(allseq) 

測試文件:

this is 
some input 

輸出:

[['t', 'h', 'i', 's', ' ', 'i', 's'], ['s', 'o', 'm', 'e', ' ', 'i', 'n', 'p', 'u', 't']] 

爲了澄清爲什麼需要第二次修正,當你追加一個對象名單,對對象的引用放在列表中。因此,如果稍後改變該對象,列表的顯示內容將發生變化,因爲它會引用同一個對象。 seq[:] = []將原始列表變爲空白。

>>> allseq = [] 
>>> seq = [1,2,3] 
>>> allseq.append(seq) 
>>> allseq    # allseq contains seq 
[[1, 2, 3]] 
>>> seq[:] = []   # seq is mutated to be empty 
>>> allseq    # since allseq has a reference to seq, it changes too. 
[[]] 
>>> seq.append(1)   # change seq again 
>>> allseq    # allseq's reference to seq displays the same thing. 
[[1]] 
>>> allseq.append(seq) # Add another reference to the same list 
>>> allseq     
[[1], [1]] 
>>> seq[:]=[]    # Clearing the list shows both references cleared. 
>>> allseq 
[[], []] 

你可以看到,allseq包含id()於SEQ同樣引用:

>>> id(seq) 
46805256 
>>> id(allseq[0]) 
46805256 
>>> id(allseq[1]) 
46805256 

seq = []創建一個新的列表,並附有不同的ID,而不是突變相同的列表。

+0

哦,我應該指出他出錯的地方。感謝您填寫!除了學習更好的方法來實現他的目標之外,OP能夠從他的錯誤中吸取教訓,這絕對有用。 –

0

如果你或其他人,喜歡一個襯墊,這裏是(根據皮爾斯達拉赫的出色答卷):

allseq = [list(line.strip()) for line in open("input.txt").readlines()] 
相關問題