Python列表索引获取

一、字符串索引获取

1、.find() 

#字符串
stringA = "huo qu suo yin"
 
#获取o的索引并打印
index_o = stringA.find("o")
print(index_o)
2

进程已结束,退出代码0

  只适用于字符串,并且只能输出最近位置的索引,不能输出全部

2、.index() 

#字符串
stringA = "huo qu suo yin"
#获取o的索引并打印
index_o = stringA.index("o")
print(index_o)
 
#列表
listA = ["o", "u" , "i"]
#获取u的索引并打印
index_u = listA.index("u")
print(index_u)

# 2
# 1

# 进程已结束,退出代码0

 适用于字符串和列表,并且只能输出最近位置的索引,不能输出全部

3、re.finditer() 

#引用正则表达式模块
import re
 
#字符串
stringA = "huo qu suo yin"
 
#获取所有o元素的索引
list_index = [i.start() for i in re.finditer("o",stringA)]
 
print(list_index)
[2, 9]

进程已结束,退出代码0

可以返回字符串中多个重复字符的索引

二、列表索引获取

1、.index()

list = [0,1,1,1,2,3]

# 获取所有o元素的索引
list.index(1)

print(list.index(1))
# 1

2、enumerate()

def get_index1(lst=None, item=''):
    return [index for (index,value) in enumerate(lst) if value == item]
lst = ['A', 1, 4, 2, 'A', 3]
get_index1(lst, 'A')
print(get_index1(lst, 'A'))
[0, 4]

进程已结束,退出代码0
def get_index1(lst, item):
    return [index for (index,value) in enumerate(lst) if value == item]
lst = ['A', 1, 4, 2, 'A', 1]
get_index1(lst, 1)
print(get_index1(lst,1))
[1, 5]

进程已结束,退出代码0

3、range()

def get_index3(lst=None, item=''):
    return [i for i in range(len(lst)) if lst[i] == item]
lst = ['A', 1, 4, 2, 'A', 3]
get_index1(lst, 'A')
# [0, 4]

猜你喜欢

转载自blog.csdn.net/weixin_57399429/article/details/128172250