簡単な方法(@Pierceの回答)があるにもかかわらず、元のコードには2つの問題があります。第二は理解することが重要です。
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
出力:第2回修正が必要な理由
[['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()
で、配列に同じ参照番号が含まれて見ることができます:
>>> id(seq)
46805256
>>> id(allseq[0])
46805256
>>> id(allseq[1])
46805256
seq = []
ではなく、同じリストを変異の、異なるIDを持つ新しいリストを作成します。
ありがとうございました!これはもっと洗練されたソリューションです。 – Matt
@Matt、問題ありません!どこかで始まらなければならない! :) –