如何从列表中删除空字符串?我试过这样:
starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']
output = filter(bool, starring)
我想要的输出:
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']
但output
最终与input
相同。传递给filter
的正确功能是什么?
答案 0 :(得分:22)
只有空字符串的计算结果为False
,因此您需要使用strip()
删除任何空格,然后我们可以依赖非空字符串进行评估为真。
>>> 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']
虽然列表理解可能更容易:
>>> [name for name in starring if name.strip()]
['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah']
答案 1 :(得分:7)
您可以删除尾随和前导空格,如果只包含空格,则会产生空字符串。
列表理解:
l = [x for x in l if x.strip()]
使用filter
和operator.methodcaller
[docs]:
l = filter(operator.methodcaller('strip'), l)
或更简单:
l = filter(str.strip, l)
如果您想要向该方法传递其他参数, operator.methodcaller
将是唯一的方法。
答案 2 :(得分:1)
s = ['Vashu Bhagnani', 'Khemchand Bhagnani', '', 'Jacky Bhagnani', '', 'Prashant Shah', '']
[a for a in s if len(a) > 0]