Python: list查找元素操作

not in

在Python中,not in 是一个逻辑运算符,用于检查一个元素是否不在一个列表(list)中。

如果元素不在列表中,not in 返回 True,否则返回 False

语法:

element not in list

其中,element 是要检查的元素,list 是要检查的列表。

示例:

my_list = [1, 2, 3, 4, 5]  
  
if 3 not in my_list:  
    print("3 不在列表中")  
else:  
    print("3 在列表中")

      在这个示例中,我们检查数字 3 是否不在列表 my_list 中。因为 3 不在 my_list 中,所以输出为 "3 不在列表中"。

in

在Python中,in 是一个成员运算符,用于检查一个元素是否存在于列表(list)中。如果元素存在于列表中,in 返回 True,否则返回 False

语法:

element in list

其中,element 是要检查的元素,list 是要检查的列表。

示例:

my_list = [1, 2, 3, 4, 5]  
  
if 3 in my_list:  
    print("3 在列表中")  
else:  
    print("3 不在列表中")

在这个示例中,我们检查数字 3 是否在列表 my_list 中。因为 3 存在于 my_list 中,所以输出为 "3 在列表中"。

index()

在Python中,index() 是列表(list)对象的一个方法,用于返回列表中某个元素的第一个匹配项的索引。如果元素不存在于列表中,index() 会抛出一个 ValueError 异常。

语法:

list.index(item)

其中,item 是你要查找其索引的元素。

示例:

my_list = ['apple', 'banana', 'cherry', 'date']  
  
print(my_list.index('cherry'))  # 输出:2

 count()

在Python中,count() 是列表(list)对象的一个方法,用于返回列表中某个元素的出现次数。

 语法:

list.count(item)

其中,item 是你要计算出现次数的元素。

示例:

my_list = [1, 2, 3, 2, 4, 2, 5]  
print(my_list.count(2))  # 输出:3

在这个示例中,我们计算数字 2 在列表 my_list 中出现的次数。因为 2 在列表中出现了三次,所以输出为 3

猜你喜欢

转载自blog.csdn.net/Ethan_Rich/article/details/135022948