2016-11-06 131 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()] 
相关问题