在Python中获取列表或数组元素的下标可以通过以下几种方法:
1. 使用`enumerate`函数:
my_list = ['apple', 'banana', 'cherry']for index, value in enumerate(my_list):print(index, value)
输出:
0 apple1 banana2 cherry
2. 使用`range`函数结合`len`函数:
my_list = ['apple', 'banana', 'cherry']for i in range(len(my_list)):print(i, my_list[i])
输出与上面相同。
3. 使用`numpy`库的`ndenumerate`函数(适用于大规模数据):

import numpy as npmy_array = np.array(['apple', 'banana', 'cherry'])for index, value in np.ndenumerate(my_array):print(index, value)
输出:
(0, 'apple')(1, 'banana')(2, 'cherry')
4. 使用`numpy`的`where`方法寻找数组中的某个值:
import numpy as npvector = np.array([5, 10, 15, 20])a = np.where(vector == 10)print(a) 输出:(array(, dtype=int64),)print(a) 输出:1
5. 使用列表推导式结合`enumerate`来获取特定值的索引:
word = ['dislike', ' is ', 'life', 'like', ' long ', 'python', 'short', 'too', ' is ']word1 = [i for i, x in enumerate(word) if x == ' is ']print(word1) 输出:[1, 8]
以上方法可以帮助你在Python中获取列表或数组元素的下标
