Python过滤列表,删除\'n'和空字符串

时间:2018-09-12 12:15:53

标签: python-3.x list dictionary filter

我有一个列表,我尝试删除空字符串和'\ n'

re = ['\n', '\n', '0 / 6\n', '1 / 6\n', '2 / 6\n', '3 / 6\n', '4 / 6\n', '5 / 6\n', '6 / 6\n', '\n', 'mobile\n']

resul = map(str.rstrip, re)
print(list(resul))

str_list = filter(None, list(resul))
print(list(str_list))

输出:

['', '', '0 / 6', '1 / 6', '2 / 6', '3 / 6', '4 / 6', '5 / 6', '6 / 6', '', 'mobile']
[]

因此,第一个输出是正确的,我成功删除了\n,但是当我想删除空的strinf之后,列表就很简单了。

2 个答案:

答案 0 :(得分:0)

从列表中获取所有非\n值,并通过列表理解删除\n

re = ['\n', '\n', '0 / 6\n', '1 / 6\n', '2 / 6\n', '3 / 6\n', '4 / 6\n', '5 / 6\n', '6 / 6\n', '\n', 'mobile\n']

print([x.replace('\n', '') for x in re if x != '\n'])
# ['0 / 6', '1 / 6', '2 / 6', '3 / 6', '4 / 6', '5 / 6', '6 / 6', 'mobile']

答案 1 :(得分:0)

您得到一个空列表,只是因为您正在将resul转换为列表,然后调用filter来消耗{({1 }}对象,它是Python 3中的生成器。您实际上是将一个空生成器传递给map

如果删除过早转换到列表,您将获得预期的输出:

map
相关问题