Python list index acquisition

1. String index acquisition

1、.find() 

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

进程已结束,退出代码0

  Only applicable to strings, and can only output the index of the nearest position, not all

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

 Applicable to strings and lists, and can only output the index of the nearest position, not all

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

Can return the index of multiple repeated characters in a string

Second, list index acquisition

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]

Guess you like

Origin blog.csdn.net/weixin_57399429/article/details/128172250