瞭解 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

更新於: 04-Jun-2020

195 次檢視

開啟您的 職業

透過完成課程取得認證

開始
廣告
© . All rights reserved.