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

开启您的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.