Geo*_*ows 111 python list strip
我必须在表格中列出大量的单词:
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
Run Code Online (Sandbox Code Playgroud)
然后使用条带功能,将其转换为:
['this', 'is', 'a', 'list', 'of', 'words']
Run Code Online (Sandbox Code Playgroud)
我以为我写的东西会起作用,但我一直都会收到错误说:
"'list'对象没有属性'strip'"
这是我试过的代码:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 192
>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']
Run Code Online (Sandbox Code Playgroud)
Sch*_*uki 56
您可以使用列表推导:
strip_list = [item.strip() for item in lines]
Run Code Online (Sandbox Code Playgroud)
或者map功能:
# with a lambda
strip_list = map(lambda it: it.strip(), lines)
# without a lambda
strip_list = map(str.strip, lines)
Run Code Online (Sandbox Code Playgroud)
[w.strip() for w in ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
Run Code Online (Sandbox Code Playgroud)