Python程序在元组列表中查找具有正元素的元组
给定一个元组列表。任务是获取所有具有所有正元素的元组。
例子:
Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)]
Output : [(4, 5, 9)]
Explanation : Extracted tuples with all positive elements.
Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)]
Output : []
Explanation : No tuple with all positive elements.
方法 #1:使用列表理解 + all()
在此,all() 用于检查所有元组,列表理解有助于元组的迭代。
Python3
# Python3 code to demonstrate working of
# Positive Tuples in List
# Using list comprehension + all()
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
# printing original list
print("The original list is : " + str(test_list))
# all() to check each element
res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]
# printing result
print("Positive elements Tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Positive Tuples in List
# Using filter() + lambda + all()
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
# printing original list
print("The original list is : " + str(test_list))
# all() to check each element
res = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list))
# printing result
print("Positive elements Tuples : " + str(res))
输出
原始列表是:[(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
正元素元组:[(4, 5, 9), (4, 6)]
原始列表是:[(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
正元素元组:[(4, 5, 9), (4, 6)]
方法 #2:使用 filter() + lambda + all()
在此,过滤任务是使用 filter() 和 lambda 函数执行的。
Python3
# Python3 code to demonstrate working of
# Positive Tuples in List
# Using filter() + lambda + all()
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
# printing original list
print("The original list is : " + str(test_list))
# all() to check each element
res = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list))
# printing result
print("Positive elements Tuples : " + str(res))
输出
原始列表是:[(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
正元素元组:[(4, 5, 9), (4, 6)]
原始列表是:[(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
正元素元组:[(4, 5, 9), (4, 6)]