[英]Remove strings containing only white spaces from list
How do I delete empty strings from a list? 如何从列表中删除空字符串? I tried like this:
我试过这样的:
starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']
output = filter(bool, starring)
Output I want: 我想要的输出:
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']
But output
ends up being the same as input
. 但
output
最终与input
相同。 What's the correct function to pass to filter
? 传递给
filter
的正确功能是什么?
Only the empty string evaluates to False
so you need to use strip()
to remove any whitespace and we can then rely on non-blank strings being evaluated as true. 只有空字符串的计算结果为
False
因此您需要使用strip()
来删除任何空格,然后我们可以依赖于非空字符串被评估为true。
>>> starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']
>>> starring = filter(lambda name: name.strip(), starring)
>>> starring
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']
Although a list comprehension might be easier: 虽然列表理解可能更容易:
>>> [name for name in starring if name.strip()]
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']
You can remove trailing and leading white spaces, which will result in an empty string if it only contains those. 您可以删除尾随和前导空格,如果只包含那些空格,则会产生空字符串。
List comprehension: 列表理解:
l = [x for x in l if x.strip()]
With filter
and operator.methodcaller
[docs] : 使用
filter
和operator.methodcaller
[docs] :
l = filter(operator.methodcaller('strip'), l)
or simpler: 或者更简单:
l = filter(str.strip, l)
operator.methodcaller
would be the only way if you'd want to pass additional arguments to the method. 如果您想要向该方法传递其他参数,
operator.methodcaller
将是唯一的方法。
s = ['Vashu Bhagnani', 'Khemchand Bhagnani', '', 'Jacky Bhagnani', '', 'Prashant Shah', '']
[a for a in s if len(a) > 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.