Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表没有属性条_Python_Python 2.7_List_Strip - Fatal编程技术网

Python 列表没有属性条

Python 列表没有属性条,python,python-2.7,list,strip,Python,Python 2.7,List,Strip,我从一个文件中读取并将每个字符存储在一个二维数组中。我试图去掉每行末尾的“\n”。到目前为止,我的代码是: l = [] for i in range(5): l.append([]) f = open('file.txt','r') count = 0 for line in f: for char in line: l[count].append(char) count += 1 f.close() l[0].rstrip('\n') 我尝试了而

我从一个文件中读取并将每个字符存储在一个二维数组中。我试图去掉每行末尾的“\n”。到目前为止,我的代码是:

l = []
for i in range(5):
    l.append([])
f = open('file.txt','r')
count = 0
for line in f:
    for char in line:
        l[count].append(char)
    count += 1

f.close()

l[0].rstrip('\n')
我尝试了而不是
l[0]。rstrip('\n')

l=map(λs:s.strip('\n'),l)
l=[i.rstrip()表示l中的i]


每一个都返回一个错误,即列表没有属性条(或rstrip)。有没有办法解决这个问题

l
是一个列表列表。因此,如果调用
l[0].rstrip()
可以在子列表上调用
rstrip()
。但是,即使
strip()
可以工作,您也不会看到任何差异,因为字符串是不可变的,因此它将返回一个新字符串,而不是更新旧字符串

但是,您可以轻松地使用:

l[0] = [x.rstrip('\n') for x in l[0]]
仅更新
l[0]

如果要更新所有子列表,可以使用以下列表:

l = [[x.rstrip('\n') for x in s] for s in l]
此外,将文件读入内存的代码非常奇怪:只有当文件少于六行时,它才能工作。您可以使用以下方法:

with open('file.txt','r') as f:
    l = [list(line.rstrip('\n')) for line in f]

这将替换问题中的整个代码片段。

如果是
\n
,为什么不将
char
附加到
l[count]
?列表没有
strip()
,字符串有。您是想在每个
l[count]
中创建一个字符串,还是真的要创建一个单个字符的列表?
strip
用于字符串,所以在执行其他工作之前,请将其应用于字符串:
for char in line.strip():
我在
l[count].append(char)之前添加了一个if语句
来检查char是否为'\n',并删除了
l[0].rstrip('\n')
,它现在可以工作了。