如何删除列表中的特定重复数字?

时间:2016-10-01 01:32:40

标签: python list

例如我有

[3, 4, 5, 5, 12, 13, 0, 0, 0, 8, 15, 17, 0, 0, 0]

我想删除所有零。 注意:假设我们在列表中具有未知数量的零,其长度未知。

1 个答案:

答案 0 :(得分:4)

列表推导使这很容易:

new_list = [x for x in orig_list if x != 0]

您可以使用filter将工作推送到C图层:

# If they're all numbers, you can avoid work by using filter with None:
new_list = list(filter(None, orig_list))  # List wrapper not needed on Py2

# If falsy values that aren't numeric zero might be found, and should be kept, you'd do:
new_list = list(filter((0).__ne__, orig_list))  # List wrapper not needed on Py2