Python – 用整数过滤元组
给定元组列表,过滤只有 int 数据类型的元组。
Input : [(4, 5, “GFg”), (3, ), (“Gfg”, )]
Output : [(3, )]
Explanation : 1 tuple (3, ) with all integral values.
Input : [(4, 5, “GFg”), (3, “Best” ), (“Gfg”, )]
Output : []
Explanation : No tuple with all integers.
方法 #1:使用循环 + isinstance()
在此,我们迭代每个元组并使用 isinstance() 检查除 int 以外的数据类型,如果找到的元组被标记为关闭并被忽略。
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using loop + isinstance()
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
# printing original list
print("The original list is : " + str(test_list))
res_list = []
for sub in test_list:
res = True
for ele in sub:
# checking for non-int.
if not isinstance(ele, int):
res = False
break
if res :
res_list.append(sub)
# printing results
print("Filtered tuples : " + str(res_list))
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using all() + list comprehension + isinstance()
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to encapsulate in 1 liner
res = [sub for sub in test_list if all(isinstance(ele, int) for ele in sub)]
# printing results
print("Filtered tuples : " + str(res))
输出
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )]
Filtered tuples : [(5, 6), (3, )]
方法 #2:使用 all() + 列表理解 + isinstance()
在此,all() 用于使用 isinstance() 检查所有元素是否为整数,如果检查,则将元组添加到结果中。
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using all() + list comprehension + isinstance()
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to encapsulate in 1 liner
res = [sub for sub in test_list if all(isinstance(ele, int) for ele in sub)]
# printing results
print("Filtered tuples : " + str(res))
输出
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )]
Filtered tuples : [(5, 6), (3, )]