Python 查詢元組中的列表數
元的 Python 是有序並且不可改變的。但它由列表作為元素時也可以被組成。鑑於由列表組成的元組,我們瞭解元組中有多少個列表。
使用 len()
在此方法中,我們將應用 len 函式。len() 函式將提供此元組元素的列表數。
示例
tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])
print("The number of lists in tupA :\n" , len(tupA))
print("The number of lists in tupB :\n" , len(tupB))輸出
執行以上程式碼,我們將獲得以下結果 -
The number of lists in tupA : 2 The number of lists in tupB : 3
使用 UDF
在我們必須一遍又一遍地使用此操作的情況下,我們很好地定義一個函式。這個函式將檢查我們傳遞的元素是否為元組。然後應用 len 函式計算元素數,即其中的列表。
示例
tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])
def getcount(tupl):
if isinstance(tupl, tuple):
return len(tupl)
else:
pass
print("The number of lists in tupA :\n" , getcount(tupA))
print("The number of lists in tupA :\n" , getcount(tupB))輸出
執行以上程式碼,我們將獲得以下結果 -
The number of lists in tupA : 2 The number of lists in tupA : 3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP