即使有更簡單的方法(@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,而不是突變相同的列表。
謝謝!這是一個更優雅的解決方案。 – Matt
@Matt,沒問題!要開始某處! :) –