查找所有元组在Python中是否具有相同的长度
在本文中,我们将找出给定列表中的所有元组是否具有相同的长度。
与伦
我们将使用len函数并将其结果与我们正在验证的给定值进行比较。如果值相等,那么我们认为它们的长度相同,否则就不一样。
示例
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res = 1
# Iteration
for tuple in listA:
if len(tuple) != k:
res = 0
break
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length")输出结果
运行上面的代码给我们以下结果-
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same length与所有人和伦
我们将len函数alogn与all函数一起使用,并使用for循环遍历列表中存在的每个元组。
示例
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res=(all(len(elem) == k for elem in listA))
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length")输出结果
运行上面的代码给我们以下结果-
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same length热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西