编辑列表列表中的字符串 [英] Editing strings in a list of lists
问题描述
我从一个文本块中制成了一个列表列表,其中每个列表包含一行中的所有单词作为单独的元素,如下所示:
I've made a list of lists from a text block where each list contains all the words in a line as a separate element, like this:
listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n']
['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
我希望能够在列表列表中移动,并从列表列表中每个列表的最后一个元素中删除"\ n".
I want to be able to move through the list of lists, and remove the '\n' from the last element of each list in the list of lists.
这是我为尝试执行此操作而编写的脚本,但是它不起作用,因为当我返回n时,它仅返回第一个列表的第一个元素.
This is the script I wrote to try to do this, but it doesn't work because when I return n, it only returns the first element of the first list.
def remove_linebreaks(input):
for i in data:
for n in i:
if '\n' in n:
n.strip('\n')
return n
else:
return n
return input
还有其他方法可以做到吗?
Are there any other ways I could do this?
推荐答案
只需遍历每个列表,并将最后一个元素替换为带有'\n'
的最后一个元素.
Just iterate over each list and replace the last element with the last element with the '\n'
stripped.
>>> listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],
['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
>>> for elem in listoflists:
elem[-1] = elem[-1].strip('\n')
>>> listoflists
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
编辑-由于在代码中,您似乎正在从可能执行的每个元素中剥离\n
EDIT - Since in the code, you seem to be stripping \n
from each element you could do
>>> [[elem.strip('\n') for elem in lst] for lst in listoflists]
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
这篇关于编辑列表列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!