Python - 从列表中删除每个元素都为 None 的元组
给定一个元组列表,删除所有值为 None 的元组。
Input : test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]
Output : [(None, 2), (3, 4), (12, 3)]
Explanation : All None tuples are removed.
Input : test_list = [(None, None), (None, None), (3, 4), (12, 3), (None, )]
Output : [(3, 4), (12, 3)]
Explanation : All None tuples are removed.
方法 #1:使用all() +列表推导式
在这里,我们使用 all() 来检查所有 None 值是否被丢弃,列表理解会执行迭代任务。
Python3
# Python3 code to demonstrate working of
# Remove None Tuples from List
# Using all() + list comprehension
# initializing list
test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]
# printing original list
print("The original list is : " + str(test_list))
# negating result for discarding all None Tuples
res = [sub for sub in test_list if not all(ele == None for ele in sub)]
# printing result
print("Removed None Tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove None Tuples from List
# Using filter() + lambda + all()
# initializing list
test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]
# printing original list
print("The original list is : " + str(test_list))
# filter() + lambda to drive logic of discarding tuples
res = list(filter(lambda sub : not all(ele == None for ele in sub), test_list))
# printing result
print("Removed None Tuples : " + str(res))
输出:
The original list is : [(None, 2), (None, None), (3, 4), (12, 3), (None,)]
Removed None Tuples : [(None, 2), (3, 4), (12, 3)]
方法 #2:使用filter() + lambda + all()
在此方法中,过滤 None 元组的任务是使用 filter() 和 lambda函数完成的,以使用 all() 提供 None 检查功能。
蟒蛇3
# Python3 code to demonstrate working of
# Remove None Tuples from List
# Using filter() + lambda + all()
# initializing list
test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]
# printing original list
print("The original list is : " + str(test_list))
# filter() + lambda to drive logic of discarding tuples
res = list(filter(lambda sub : not all(ele == None for ele in sub), test_list))
# printing result
print("Removed None Tuples : " + str(res))
输出:
The original list is : [(None, 2), (None, None), (3, 4), (12, 3), (None,)]
Removed None Tuples : [(None, 2), (3, 4), (12, 3)]