python中list的五种查找方法

Python中是有查找功能的,五种方式:in、not in、count、index,find 前两种方法是保留字。

下面以my_list = [‘a’,‘b’,‘c’,‘hello’],my_str = ‘abcde’,为例作介绍:

in 操作符

判断值是否在列表中:

'a' in my_list

not in 操作符

判断值是否不在列表中:

'a' not in my_list

count方法

统计指定值在列表中出现的次数:

my_list.count('a')

index 方法

查看指定值在列表中的位置:

# 返回a在列表中首次出现的位置
my_list.index('a')
# 返回a在指定切片内第一次出现的位置
my_list.index('a')

find方法

仅用于string,不可用于list
如果找到则返回第一个匹配的位置,如果没找到则返回-1,而如果通过index方法去查找的话,没找到的话会报错。

my_str.find('a')

技巧

index = a_list.index('a') if ('a' in a_list) else -1
[x for x in test if 'a' in x]

猜你喜欢

转载自blog.csdn.net/weekdawn/article/details/125989243
今日推荐