計算 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”。
  • 在控制檯上顯示為輸出。

更新時間:12-Mar-2021

119 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告