在 Python 元组中查找给定数据类型的频率
元组是 Python 中一种流行的数据类型,它表示由逗号分隔的对象或元素的集合。数据类型的频率定义了特定变量类型的总计数。Python 有四种基本变量类型:整数、浮点数、布尔值和字符串。在 Python 中,我们有一些内置函数,例如 type()、isinstance()、filter()、lambda、len() 和 list(),将用于查找 Python 元组中给定数据类型的频率。
语法
以下语法在示例中使用 -
type()
type() 是 Python 中一个内置函数,它返回类型对象。
isinstance()
isinstance() 是 Python 中一个内置函数,它将值与给定类型进行集成。
filter()
filter() 方法在根据特定条件过滤项目时应用。简单来说,它允许用户迭代那些提取以满足条件的元素。
lambda
lambda 函数提供了一种使用 lambda 关键字声明简短匿名函数的快捷方式。lambda 函数的行为与使用 def 关键字表达时相同。
len()
len() 是 Python 中一个内置函数,它返回对象的长度。
list()
list() 是 Python 中一个内置函数,它将任何值转换为列表形式。
使用简单的 for 循环
在此程序中,变量 count 将初始值存储为 0,这将在计数器递增期间使用。然后使用 for 循环,其中变量 i 遍历给定的输入元组,即 t。接下来,if 语句设置 type()(返回特定类型)与 d_type 之间等价的条件。现在变量 count 增加 1,它查找特定数据类型的频率。最后,函数返回生成结果。
示例
# recursive function
def total_freq(t, d_type):
count = 0
for i in t:
if type(i) == d_type:
count += 1
return count
# The tuple elements
my_tup = (5, 8.9, "Box", 3.3, "CAR", 7, 1.0)
# Set the datatype as float
datatype = float
# Calling function
freq = total_freq(my_tup, datatype)
print("The frequency of", datatype, ":\n", freq)
输出
The frequency of <class 'float'> : 3
使用列表推导式
在以下示例中,我们将通过定义一个名为 data_freq_count() 的函数开始程序,该函数接受两个参数 - t 和 datatype,以通过函数调用从变量 my_tup 和 d_type 中获取值。接下来,函数返回使用内置函数 sum() 生成值 1,其中变量 item 遍历变量 t。使用 if 语句,它将条件设置为 type() 等于变量 datatype,它查找属于特定数据类型的元素。最后,它将显示结果。
示例
def data_freq_count(t, datatype):
return sum(1 for item in t if type(item) == datatype)
my_tup = (1, 'A', 2, 'B', 3.9, 15, 0, 'True')
# Set the datatype as an integer
d_type = int
freq = data_freq_count(my_tup, d_type)
print("The total count of integer frequency is ", freq)
输出
The total count of integer frequency is 4
使用 isinstance() 函数
在以下示例中,变量 cnt 初始化为初始值 0,这将在输入元组的迭代期间使用。使用 for 循环,变量 i 迭代变量 t 中的每个单个元组元素。接下来,它将使用 if 语句将条件设置为内置函数 isinstance(),该函数接受两个参数 - i 和 d,它们比较给定元组中存在的特定数据类型的值。然后使用 += 运算符将变量 cnt 增加 1 并返回程序的结果。
示例
def data_freq_count(t, d):
cnt = 0
for i in t:
if isinstance(i, d):
cnt += 1
return cnt
# The input tuple elements
my_tup = (5, 'abc', 2, 4.8, 7.2, 'is', 4.0)
# Set the datatype as string
d_type = str
# Calling function
freq = data_freq_count(my_tup, d_type)
print("The total frequency of string datatype:", freq)
输出
The total frequency of string datatype: 2
使用 filter() 函数
该程序使用两个输入变量 - my_tuple 和 d_type 分别存储值作为元组和 bool 数据类型。这些变量的值将由名为 data_freq_count() 的函数获取,该函数接受两个参数 - t 和 d 以对数据类型频率的操作进行处理。然后它将使用内置的 filter(),它接受 lambda 作为参数来计算特定数据类型的总计数。接下来,函数返回将使用内置函数 len() 和 list() 生成输出。
示例
def data_freq_count(t, d):
filtered_tuple = filter(lambda item: type(item) == d, t)
return len(list(filtered_tuple))
# Initialize the tuple
my_tuple = (5, "PYTHON", 40.0, "JAVA", 5.0, True, False)
d_type = bool
# Calling function
freq = data_freq_count(my_tuple, d_type)
print("The frequency of float datatype:", freq)
输出
The frequency of float datatype: 2
结论
我们讨论了设置特定数据类型并查找其频率的各种方法。使用了各种内置函数,例如 filter()、type() 等,以满足特定条件和操作的需求。此类程序可以作为数据操作和数据分析(如统计分析和机器学习应用)的参考。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP