Python 程式查詢元組的長度


當需要查詢元組的長度時,可以使用“sizeof”方法。

以下是演示:

示例

 動態演示

import sys
tuple_1 = ("A", 1, "B", 2, "C", 3)
tuple_2 = ("Java", "Lee", "Code", "Mark", "John")
tuple_3 = ((1, "Bill"), ( 2, "Ant"), (3, "Fox"), (4, "Cheetah"))

print("The first tuple is :")
print(tuple_1)
print("The second tuple is :")
print(tuple_2)
print("The third tuple is :")
print(tuple_3)
print("Size of first tuple is : " + str(sys.getsizeof(tuple_1)) + " bytes")
print("Size of second tuple is : " + str(sys.getsizeof(tuple_2)) + " bytes")
print("Size of third tuple is: " + str(sys.getsizeof(tuple_3)) + " bytes")

輸出

The first tuple is :
('A', 1, 'B', 2, 'C', 3)
The second tuple is :
('Java', 'Lee', 'Code', 'Mark', 'John')
The third tuple is :
((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah'))
Size of first tuple is : 96 bytes
Size of second tuple is : 88 bytes
Size of third tuple is : 80 bytes

解釋

  • 匯入所需程式包。

  • 定義元組並在控制檯上顯示。

  • 對每個元組呼叫“sizeof”方法,並將長度顯示為控制檯上的輸出。

更新於: 17-4-2021

321 次瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告