Python – 检查列表中所有元素是否相同


有时我们需要检查列表元素中是否存在单个重复值。我们可以使用以下 Python 程序来检查这种情况。有多种方法。

使用 for 循环

在这种方法中,我们从列表中获取第一个元素,并使用传统的for 循环将每个元素与第一个元素进行比较。如果任何元素的值不匹配,则我们退出循环,结果为假。

示例

 在线演示

List = ['Mon','Mon','Mon','Mon']
result = True
# Get the first element
first_element = List[0]
# Compares all the elements with the first element
for word in List:
   if first_element != word:
      result = False
      print("All elements are not equal")
      break
   else:
      result = True
   if result:
      print("All elements are equal")

运行以上代码,得到以下结果:

All elements are equal
All elements are equal 
All elements are equal 
All elements are equal

使用 all()

all() 方法对列表中的每个元素应用比较。它类似于我们在第一种方法中所做的,但我们使用的是all() 方法,而不是for循环。

示例

 在线演示

List = ['Mon','Mon','Tue','Mon']
# Uisng all()method
result = all(element == List[0] for element in List)
if (result):
   print("All the elements are Equal")
else:
   print("All Elements are not equal")

运行以上代码,得到以下结果:

All the elements are not Equal

使用 count()

Python 列表方法 count()返回元素在列表中出现的次数。因此,如果列表中重复了相同的元素,则使用len()得到的列表长度将与使用count()得到的元素在列表中出现的次数相同。下面的程序使用了这个逻辑。

示例

 在线演示

List = ['Mon','Mon','Mon','Mon']
# Result from count matches with result from len()
result = List.count(List[0]) == len(List)
if (result):
   print("All the elements are Equal")
else:
   print("Elements are not equal")

运行以上代码,得到以下结果:

All the elements are Equal

更新于:2023年8月27日

27K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.