Python – 从元组中删除特定的数据类型元素
有时,在使用Python元组时,我们可能会遇到需要从元组中删除特定数据类型元素的问题。这种问题可能发生在需要数据预处理的领域。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (4, 5, ‘Gfg’, 7.7, ‘Best’), data_type = str
Output : [4, 5, 7.7]
Input : test_tuple = (4, 5, ‘Gfg’, 7.7, ‘Best’), data_type = float
Output : [4, 5, ‘Gfg’, ‘Best’]
方法 #1:使用循环 + isinstance()
上述功能的组合可以用来解决这个问题。在这种情况下,我们需要使用 isinstance() 对每个元素进行迭代,并在它与数据类型匹配时丢弃该元素。
# Python3 code to demonstrate working of
# Remove particular data type Elements from Tuple
# Using loop + isinstance()
# initializing tuple
test_tuple = (4, 5, 'Gfg', 7.7, 'Best')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing data type
data_type = int
# Remove particular data type Elements from Tuple
# Using loop + isinstance()
res = []
for ele in test_tuple:
if not isinstance(ele, data_type):
res.append(ele)
# printing result
print("The filtered tuple : " + str(res))
输出 :
The original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
方法 #2:使用列表理解 + isinstance()
这是可以执行此任务的另一种方式。在这种情况下,我们需要使用列表理解的速记来执行类似的任务。
# Python3 code to demonstrate working of
# Remove particular data type Elements from Tuple
# Using list comprehension + isinstance()
# initializing tuple
test_tuple = (4, 5, 'Gfg', 7.7, 'Best')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing data type
data_type = int
# Remove particular data type Elements from Tuple
# Using list comprehension + isinstance()
res = [ele for ele in test_tuple if not isinstance(ele, data_type)]
# printing result
print("The filtered tuple : " + str(res))
输出 :
The original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']