Python – 在元组中查找给定数据类型的频率
有时,在处理Python记录时,我们可能会遇到需要提取元组中出现的任何数据类型的计数的问题。这可以应用于各种领域,例如日常编程和 Web 开发。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (5, ‘Gfg’, 2, 8.8, 1.2, ‘is’), data_type = int
Output : 2
Input : test_tuple = (5, ‘Gfg’, 2, 8.8, 1.2, ‘is’), data_type = str
Output : 2
方法 #1:使用循环 + isinstance()
上述功能的组合可以用来解决这个问题。在此,我们使用 isinstance() 执行检查数据类型的任务,并运行一个计数器以在匹配时递增。
# Python3 code to demonstrate working of
# Data type frequency in tuple
# Using loop + isinstance()
# initializing tuples
test_tuple = (5, 'Gfg', 2, 8.8, 1.2, 'is')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing data type
data_type = float
# Data type frequency in tuple
# Using loop + isinstance()
count = 0
for ele in test_tuple:
if isinstance(ele, float):
count = count + 1
# printing result
print("The data type frequency : " + str(count))
输出 :
The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The data type frequency : 2
方法 #2:使用sum()
+ isinstance()
上述功能的组合也可以用来解决这个问题。这使用了与上述方法类似的解决方法,只是使用 sum() 进行计数的简写方式。
# Python3 code to demonstrate working of
# Data type frequency in tuple
# Using sum() + isinstance()
# initializing tuples
test_tuple = (5, 'Gfg', 2, 8.8, 1.2, 'is')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing data type
data_type = float
# Data type frequency in tuple
# Using sum() + isinstance()
count = sum(1 for ele in test_tuple if isinstance(ele, data_type))
# printing result
print("The data type frequency : " + str(count))
输出 :
The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The data type frequency : 2