我在2D列表中有问题:

t = [['\n'], ['1', '1', '1', '1\n']]


我想从嵌套列表中删除"\n"

最佳答案

您可以剥离嵌套列表中的所有字符串:

t = [[s.strip() for s in nested] for nested in t]


这将从每个字符串的开头和结尾删除所有空格(空格,制表符,换行符等)。

如果需要更精确,请使用str.rstrip('\n')

t = [[s.rstrip('\n') for s in nested] for nested in t]


如果还需要删除空值,则可能必须过滤两次:

t = [[s.rstrip('\n') for s in nested if not s.isspace()] for nested in t]
t = [nested for nested in t if nested]


如果第一行只包含一个空格,则第一行仅包含一个剥离的字符串,第二行则删除完全为空的列表。在Python 2中,您还可以使用:

t = filter(None, nested)


对于后一行。

关于python - Python:如何从2D列表元素中删除\n?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20680168/

10-12 23:07