Python 3
我想从列表中删除所有空值,但索引为0的元素。 换句话说,我们有两个列表:
[1, "screen", "keyboard", "mouse", , , , "router", , ,]
[, "ball", "dumbbell", "bar-bell", , , , "sneakers"]
结果应为:
[1, "screen", "keyboard", "mouse", "router"]
[, "ball", "dumbbell", "bar-bell", "sneakers"]
现在我正在尝试实现过滤器:
def delete_empty_values(a_list):
return list(filter(None, a_list))
但是此过滤器会删除所有内容,包括元素0。
好吧,使用过滤器不是教条。您能以最pythonyc的方式帮助我实现计划的内容吗?
答案 0 :(得分:0)
有以下两种方法:
[] if not a_list else [a_list[0], *filter(None, a_list[1:])]
[e for i, e in enumerate(a_list) if not (e is None and i)]