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 次浏览

开始你的 职业

通过完成课程获得认证

开始
广告