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 教师闺蜜祝福语简短