計算 Python 中第一個元組前的元素
當需要計算直到第一個元組的元素時,可以使用一個簡單迴圈、“isinstance”方法和“enumerate”方法。
以下對此做出說明 −
示例
my_tuple_1 = (7, 8, 11, 0 ,(3, 4, 3), (2, 22))
print ("The tuple is : " )
print(my_tuple_1)
for count, elem in enumerate(my_tuple_1):
if isinstance(elem, tuple):
break
print("The number of elements up to the first tuple are : ")
print(count)輸出
The tuple is : (7, 8, 11, 0, (3, 4, 3), (2, 22)) The number of elements up to the first tuple are : 4
說明
- 定義一個巢狀元組,並在控制檯上顯示。
- 列舉元組,並遍歷。
- 使用 isinstance 方法檢查元組中的元素是否屬於某一型別。
- 將此結果儲存在一個計數器之中,因為使用了“enumerate”。
- 在控制檯上顯示為輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP