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
热门推荐
10 恭喜生孩子祝福语简短
11 女孩唱生日祝福语简短
12 简短朴实的生日祝福语
13 古文毕业赠言祝福语简短
14 公司团建周年祝福语简短
15 中秋祝福语简短有深度
16 新郎婚礼致辞祝福语简短
17 新婚简短祝福语微信
18 英语快乐祝福语大全简短