即使有更简单的方法(@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,没问题!要开始某处! :) –