在 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