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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿