在 Python 中移除虚假值

Beginner

This tutorial is from open-source community. Access the source code

简介

在这个挑战中,你需要编写一个 Python 函数,用于从列表中移除虚假值。

压缩列表

编写一个函数 compact(lst),它接受一个列表作为参数,并返回一个移除了所有虚假值的新列表。虚假值包括 FalseNone0""

要解决这个问题,你可以使用 filter() 函数从列表中过滤掉虚假值。

def compact(lst):
  return list(filter(None, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) ## [ 1, 2, 3, 'a', 's', 34 ]

总结

在这个挑战中,你已经学会了如何使用 Python 中的 filter() 函数从列表中移除虚假值。