【发布时间】:2019-02-17 01:56:47
【问题描述】:
我有一个列表,我尝试删除空字符串和 '\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之后,列表是空的。
【问题讨论】:
-
res = list(filter(None, [x.strip('\n') for x in re]))怎么样? -
或
re = [x.replace("\n", "") for x in re if x.replace("\n", "") != ""] -
@OmG 因为您使用的是 Python 2,其中
map和filter返回列表。 OP 正在使用 Python 3,其中map和filter返回一个生成器
标签: python-3.x list dictionary filter