在Python中,获取列表(list)下标及其值可以通过以下几种方法:
1. 使用`for`循环和`enumerate`函数:
```python
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
print(index, item)
2. 使用`list.index()`方法获取特定值的第一个匹配下标:
```python
my_list = [72, 56, 76, 84, 80, 88]
print(my_list.index(76)) 输出:2
3. 如果需要获取列表中所有匹配值的下标,可以使用以下方法:
```python
my_list = [72, 56, 76, 84, 80, 88]
indexes = [i for i, x in enumerate(my_list) if x == 76]
print(indexes) 输出:
4. 对于更复杂的情况,比如查找列表中所有某个元素的下标,可以使用以下方法:
```python
my_list = ['hello', 'world', 'a', 'b', 'c', 1, 2, 3, 'hello', 'world', 'a', 'b', 'c', 1, 2, 3]
first_pos = 0
for i in range(my_list.count(2)):
new_list = my_list[first_pos:]
next_pos = new_list.index(2) + first_pos
print('find', first_pos, next_pos)
first_pos = next_pos 注意更新first_pos的位置
以上方法可以帮助你在Python中获取列表的下标及其值