📜  从Python中的列表中删除虚假值

📅  最后修改于: 2022-05-13 01:54:50.274000             🧑  作者: Mango

从Python中的列表中删除虚假值

先决条件: Python中的真值与假值

在Python中,计算结果为 False 的值被视为 Falsy 值。空列表、空字典、空元组、空集、空字符串、None、False、0 等值被视为假值。所以我们的任务是从 List 中删除所有 Falsy 值。

例子:

Input:  [10,20,30,0,False,40,0]
Output:  [10,20,30,40]

Input: [False,None,1,2,3,"Geeks"]
Output: [1,2,3,"Geeks"]

Input: [[],(),"GeeksForGeeks",26,27]
Output: ["GeeksForGeeks",26,27]

方法一:

我们可以创建一个包含非 Falsy 值的新列表。我们将遍历列表,并检查给定的值是真值还是假值。如果是Truthy,我们会将其添加到新列表中。现在要检查给定的值是真值还是假值,我们可以使用 bool() 方法。如果值为真,则此方法返回 True,否则返回 False。

Python3
# Python Program to remove falsy values
# from List
  
# Function returning the updated list 
def Remove_Falsy(List):
    List1 = []
    for i in List:
        if(bool(i)):
            List1.append(i)
    return List1;
              
# Original List
List1 = [10, 20, 30, 0, False, 40, 0]
List2 = [False, None, 1, 2, 3, "Geeks"]
List3 = [[], (), "GeeksForGeeks", 26, 27]
  
# printing the updated list after removing Falsy values
print("List1[] = ", Remove_Falsy(List1))
print("List2[] = ", Remove_Falsy(List2))
print("List3[] = ", Remove_Falsy(List3))


Python3
# Python Program to remove falsy values
# from List
  
# Function returning the updated list 
def Remove_Falsy(List):
    return list(filter(bool,List))
  
# Original List
List1 = [ 10, 20, 30, 0, False, 40, 0]
List2 = [ False, None, 1, 2, 3, "Geeks"]
List3 = [ [], (), "GeeksForGeeks", 26, 27]
  
# printing the updated list after removing Falsy values
print("List1[] = ", Remove_Falsy(List1))
print("List2[] = ", Remove_Falsy(List2))
print("List3[] = ", Remove_Falsy(List3))


输出:

List1[] =  [10, 20, 30, 40]
List2[] =  [1, 2, 3, 'Geeks']
List3[] =  ['GeeksForGeeks', 26, 27]

方法二:

我们可以使用 filter() 方法过滤掉虚假值。在方法 – filter(函数,sequence)中,我们将使用 bool() 方法作为 filter 方法中的参数。它将根据真值或假值返回真或假。

蟒蛇3

# Python Program to remove falsy values
# from List
  
# Function returning the updated list 
def Remove_Falsy(List):
    return list(filter(bool,List))
  
# Original List
List1 = [ 10, 20, 30, 0, False, 40, 0]
List2 = [ False, None, 1, 2, 3, "Geeks"]
List3 = [ [], (), "GeeksForGeeks", 26, 27]
  
# printing the updated list after removing Falsy values
print("List1[] = ", Remove_Falsy(List1))
print("List2[] = ", Remove_Falsy(List2))
print("List3[] = ", Remove_Falsy(List3))

输出:

List1[] =  [10, 20, 30, 40]
List2[] =  [1, 2, 3, 'Geeks']
List3[] =  ['GeeksForGeeks', 26, 27]