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