获取item 索引值
时间: 2024-01-06 20:04:39 浏览: 29
在 Python 中,可以使用`index()`方法来获取列表、元组、字符串等序列类型中某个元素的下标(或索引)。方法的语法如下:
```python
list.index(value, [start, [stop]])
```
其中,`value`表示要查找的元素,`start`表示查找的起始位置,默认为0,`stop`表示查找的终止位置,默认为序列的长度。
例如,对于以下列表:
```python
fruits = ['apple', 'banana', 'orange', 'pear']
```
我们可以使用`index()`方法来获取某个元素的下标:
```python
print(fruits.index('apple')) # 输出 0
print(fruits.index('orange')) # 输出 2
```
如果要查找的元素不存在于序列中,会抛出`ValueError`异常。例如:
```python
print(fruits.index('grape')) # 抛出 ValueError: 'grape' is not in list
```
需要注意的是,`index()`方法只返回序列中第一个匹配的元素的下标。如果要查找所有匹配的元素的下标,可以使用列表推导式或循环来实现。例如:
```python
# 使用列表推导式查找所有匹配的元素的下标
indices = [i for i in range(len(fruits)) if fruits[i] == 'apple']
print(indices) # 输出 [0]
# 使用循环查找所有匹配的元素的下标
indices = []
for i in range(len(fruits)):
if fruits[i] == 'apple':
indices.append(i)
print(indices) # 输出 [0]
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)