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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP