📌  相关文章
📜  Python|查找所有元组是否具有相同的长度

📅  最后修改于: 2022-05-13 01:54:23.115000             🧑  作者: Mango

Python|查找所有元组是否具有相同的长度

给定一个元组列表,任务是找出所有元组是否具有相同的长度。
以下是实现上述任务的一些方法。
方法#1:使用迭代

Python3
# Python code to find whether all
# tuple have equal length
 
# Input List initialization
Input = [(11, 22, 33), (44, 55, 66)]
 
# printing
print("Initial list of tuple", Input)
 
# K Initialization
k = 3
flag = 1
 
# Iteration
for tuple in Input:
    if len(tuple) != k:
        flag = 0
        break
 
# Checking whether all tuple
# have length equal to 'K' in list of tuple
if flag:
    print("All tuples have same length")
else:
    print("Tuples does not have same length")


Python3
# Python code to find whether all tuple
# have equal length
 
# Input list initialization
Input = [(11, 22, 33), (44, 55, 66), (11, 23)]
k = 2
 
# Printing
print("Initial list of tuple", Input)
 
# Using all()
Output =(all(len(elem) == k for elem in Input))
 
# Checking whether all tuple
# have equal length
if Output:
    print("All tuples have same length")
else:
    print("Tuples does not have same length")


输出:
Initial list of tuple [(11, 22, 33), (44, 55, 66)]
All tuples have same length


方法 #2:使用 all()

Python3

# Python code to find whether all tuple
# have equal length
 
# Input list initialization
Input = [(11, 22, 33), (44, 55, 66), (11, 23)]
k = 2
 
# Printing
print("Initial list of tuple", Input)
 
# Using all()
Output =(all(len(elem) == k for elem in Input))
 
# Checking whether all tuple
# have equal length
if Output:
    print("All tuples have same length")
else:
    print("Tuples does not have same length")
输出:
Initial list of tuple [(11, 22, 33), (44, 55, 66), (11, 23)]
Tuples does not have same length