檢查兩個列表在 Python 中是否相同


在 Python 資料分析中,我們可能會遇到需要比較兩個列表並找出它們是否相同(即擁有相同的元素)的情況。

示例

 線上演示

listA = ['Mon','Tue','Wed','Thu']
listB = ['Mon','Wed','Tue','Thu']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Sort the lists
listA.sort()
listB.sort()

# Check for equality
if listA == listB:
   print("Lists are identical")
else:
   print("Lists are not identical")

輸出

執行上述程式碼可獲得以下結果:

Given listA: ['Mon', 'Tue', 'Wed', 'Thu']
Given listB: ['Mon', 'Wed', 'Tue', 'Thu']
Lists are identical

使用計數器

collections 模組中的 Counter 函式可以幫助我們找出列表中每個專案的出現次數。在下面的示例中,我們還使用了兩個重複元素。如果兩個列表中每個元素的頻率都相等,我們認為這些列表是相同的。

示例

 線上演示

import collections
listA = ['Mon','Tue','Wed','Tue']
listB = ['Mon','Wed','Tue','Tue']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

# Checking again
listB = ['Mon','Wed','Wed','Tue']
print("Given listB: ",listB)

# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

輸出

執行上述程式碼可獲得以下結果:

Given listA: ['Mon', 'Tue', 'Wed', 'Tue']
Given listB: ['Mon', 'Wed', 'Tue', 'Tue']
Lists are identical
Given listB: ['Mon', 'Wed', 'Wed', 'Tue']
Lists are not identical

更新於:13-May-2020

492 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告