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

2021年3月17日15:22:13 发表评论 709 次浏览

给定一个列表, 编写一个Python程序来检查给定列表中的所有元素是否相同。

例子:

Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
Output: Yes

Input: ['Geeks', 'Is', 'all', 'Same', ]
Output: No

我们可以通过多种方式完成此任务。让我们来看看检查清单中所有元素是否相同的不同方法。

方法1:比较每个元素。

# Python program to check if all 
# ments in a List are same 
  
def ckeckList(lst):
  
     ele = lst[ 0 ]
     chk = True
      
     # Comparing each element with first item 
     for item in lst:
         if ele ! = item:
             chk = False
             break ;
              
     if (chk = = True ): print ( "Equal" )
     else : print ( "Not equal" )            
  
# Driver Code
lst = [ 'Geeks' , 'Geeks' , 'Geeks' , 'Geeks' , ]
ckeckList(lst)

输出如下:

Equal

但是在Python中, 我们可以通过许多有趣的方式完成相同的任务。

方法2:使用all()方法

# Python program to check if all 
# elements in a List are same 
res = False
  
def chkList(lst):
     if len (lst) < 0 :
         res = True
     res = all (ele = = lst[ 0 ] for ele in lst)
      
     if (res):
         print ( "Equal" )
     else :
         print ( "Not equal" )
  
# Driver Code        
lst = [ 'Geeks' , 'Geeks' , 'Geeks' , 'Geeks' ]
chkList(lst)

输出如下:

Equal

方法3:

使用count()方法

# Python program to check if all 
# elements in a List are same 
res = False
  
def chkList(lst):
     if len (lst) < 0 :
         res = True
     res = lst.count(lst[ 0 ]) = = len (lst)
      
     if (res):
         print ( "Equal" )
     else :
         print ( "Not equal" )
  
# Driver Code        
lst = [ 'Geeks' , 'Geeks' , 'Geeks' , 'Geeks' ]
chkList(lst)

输出如下:

Equal

方法4:

使用设置数据结构

因为我们知道集合中不能有重复的元素, 所以我们可以使用此属性检查所有元素是否相同。

# Python program to check if all 
# elements in a List are same 
  
def chkList(lst):
     return len ( set (lst)) = = 1
  
  
# Driver Code        
lst = [ 'Geeks' , 'Geeks' , 'Geeks' , 'Geeks' ]
  
if chkList(lst) = = True : print ( "Equal" )
else : print ( "Not Equal" )

输出如下:

Equal

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: