了解 Python 中的所有元组是否都具有相同的长度
在本文中,我们将找出给定列表中是否所有元组长度都相同。
使用 len
我们将使用 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使用 all and len
我们通过 all 函数使用 len 函数,并使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP