Python 查询元组中的列表数


元的 Python 是有序并且不可改变的。但它由列表作为元素时也可以被组成。鉴于由列表组成的元组,我们了解元组中有多少个列表。

使用 len()

在此方法中,我们将应用 len 函数。len() 函数将提供此元组元素的列表数。

示例

 现场演示

tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])

print("The number of lists in tupA :\n" , len(tupA))
print("The number of lists in tupB :\n" , len(tupB))

输出

运行以上代码,我们将获得以下结果 -

The number of lists in tupA :
2
The number of lists in tupB :
3

使用 UDF

在我们必须一遍又一遍地使用此操作的情况下,我们很好地定义一个函数。这个函数将检查我们传递的元素是否为元组。然后应用 len 函数计算元素数,即其中的列表。

示例

 现场演示

tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])

def getcount(tupl):
   if isinstance(tupl, tuple):
      return len(tupl)
   else:
      pass

print("The number of lists in tupA :\n" , getcount(tupA))
print("The number of lists in tupA :\n" , getcount(tupB))

输出

运行以上代码,我们将获得以下结果 -

The number of lists in tupA :
2
The number of lists in tupA :
3

更新于: 2020 年 8 月 26 日

289 次浏览

开启您的 职业

完成课程,获得认证

开始学习
广告
© . All rights reserved.