Python - 檢查列表中所有元素是否相同


有時列表可能包含所有相同的值。在本文中,我們將看到驗證此情況的各種方法。

使用 all 函式

我們使用 all 函式來查詢列表中每個元素與第一個元素比較的結果。如果每次比較都得到相等的結果,則結果為所有元素都相等,否則所有元素都不相等。

示例

 即時演示

listA = ['Sun', 'Sun', 'Mon']

resA = all(x == listA[0] for x in listA)

if resA:
   print("in ListA all elements are same")
else:
   print("In listA all elements are not same")
   
listB = ['Sun', 'Sun', 'Sun']
resB = all(x == listA[0] for x in listB)

if resB:
   print("In listB all elements are same")
else:
   print("In listB all elements are not same")

輸出

執行以上程式碼將得到以下結果:

In listA all elements are not same
In listB all elements are same

使用 count 函式

在這種方法中,我們計算第一個元素出現的次數,並將其與列表中元素的長度進行比較。如果所有元素都相同,則此長度將匹配,否則將不匹配。

示例

 即時演示

listA = ['Sun', 'Sun', 'Mon']

resA = listA.count(listA[0]) == len(listA)

if resA:
   print("in ListA all elements are same")
else:
   print("In listA all elements are not same")

listB = ['Sun', 'Sun', 'Sun']
resB = listB.count(listB[0]) == len(listB)

if resB:
   print("In listB all elements are same")
else:
   print("In listB all elements are not same")  

輸出

執行以上程式碼將得到以下結果:

In listA all elements are not same
In listB all elements are same

更新於: 2020-07-10

775 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.