在 Python 中查找所有元组的长度是否相同
pythonserver side programmingprogramming更新于 2026/1/22 21:00:17
在本文中,我们将找出给定列表中的所有元组的长度是否相同。
使用 len
我们将使用 len 函数并将其结果与我们正在验证的给定值进行比较。如果值相等,则我们认为它们的长度相同,否则不相同。
示例
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# 打印
print("Given list of tuple:\n", listA)
# 检查长度
k = 3
res = 1
# 迭代
for tuple in listA:
if len(tuple) != k:
res = 0
break
# 检查 res 是否为真
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 和 len
我们同时使用 len 函数和 all 函数,并使用 for 循环遍历列表中的每个元组。
示例
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# 打印
print("Given list of tuples:\n", listA)
# 检查长度
k = 3
res=(all(len(elem) == k for elem in listA))
# 检查 res 是否为真
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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

