[英]i want to remove empty string from a list
有人可以告诉我为什么我不能使用以下代码删除空字符串吗?
numlist = list()
tim = "s x s f f f"
timo = tim.strip()
for line in timo:
numlist.append(line)
list(filter(None, numlist))
print(numlist)
output: ['s', ' ', 'x', ' ', 's', ' ', 'f', ' ', 'f', ' ', 'f']
所需的 output: ['s', 'x', 's', 'f', 'f', 'f']
使用split
而不是strip
。 strip
用于删除前导和尾随字符
In [35]: tim = "s x s f f f"
In [36]: tim.split()
Out[36]: ['s', 'x', 's', 'f', 'f', 'f']
您忘记将过滤结果分配回numlist
,因此它创建了新list
并将其丢弃。 只需一行:
numlist = list(filter(None, numlist))
也就是说,它不会做你想要的,因为单个空格的字符串仍然是真实的。 如果您想将空格排除为真,一个简单的调整是:
numlist = list(filter(str.strip, numlist))
或进一步简化(但如果输入不总是带有空格分隔的单个字符,则行为不同),只需将整个代码替换为:
tim = "s x s f f f"
numlist = tim.split()
print(numlist)
因为 no-arg split
将在空白处拆分,删除前导和尾随空白,并将非空白组件list
作为单个有效操作返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.