mylist = [1, 2, 3]
1. 语法
``` python
列表序列.index(数据, 开始位置下标, 结束位置下标)
```
2. 快速体验
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
print(name_list.index(‘Lily‘, 0, 2)) # 1
```
> 注意:如果查找的数据不存在则报错。
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
print(name_list.count(‘Lily‘)) # 1
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
# 结果:True
print(‘Lily‘ in name_list)
# 结果:False
print(‘Lilys‘ in name_list)
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
# 结果:False
print(‘Lily‘ not in name_list)
# 结果:True
print(‘Lilys‘ not in name_list)
```
1. 语法
``` python
列表序列.append(数据) # 直接修改源列表
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.append(‘xiaoming‘)
# 结果:[‘Tom‘, ‘Lily‘, ‘Rose‘, ‘xiaoming‘]
print(name_list)
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.append([‘xiaoming‘, ‘xiaohong‘])
# 结果:[‘Tom‘, ‘Lily‘, ‘Rose‘, [‘xiaoming‘, ‘xiaohong‘]]
print(name_list)
```
1. 语法
```python
列表序列.extend(数据) # 参数为一个序列,如果传字符串,字符串也会被看成一个序列被追加
```
```python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.extend(‘xiaoming‘)
# 结果:[‘Tom‘, ‘Lily‘, ‘Rose‘, ‘x‘, ‘i‘, ‘a‘, ‘o‘, ‘m‘, ‘i‘, ‘n‘, ‘g‘]
print(name_list)
```
```python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.extend([‘xiaoming‘, ‘xiaohong‘])
# 结果:[‘Tom‘, ‘Lily‘, ‘Rose‘, ‘xiaoming‘, ‘xiaohong‘]
print(name_list)
```
1. 语法
``` python
列表序列.insert(位置下标, 数据)
```
2. 快速体验
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.insert(1, ‘xiaoming‘)
# 结果:[‘Tom‘, ‘xiaoming‘, ‘Lily‘, ‘Rose‘]
print(name_list)
```
1. 语法
``` python
del 目标
```
2. 快速体验
2.1 删除列表
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
# 结果:报错提示:name ‘name_list‘ is not defined
del name_list
print(name_list)
```
? 2.2 删除指定数据
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
del name_list[0]
# 结果:[‘Lily‘, ‘Rose‘]
print(name_list)
```
1. 语法
``` python
列表序列.pop(下标)
```
2. 快速体验
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
del_name = name_list.pop(1)
# 结果:Lily
print(del_name)
# 结果:[‘Tom‘, ‘Rose‘]
print(name_list)
```
1. 语法
``` python
列表序列.remove(数据)
```
2. 快速体验
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.remove(‘Rose‘)
# 结果:[‘Tom‘, ‘Lily‘]
print(name_list)
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_list.clear()
print(name_list) # 结果: []
```
``` python
num_list = [1, 5, 2, 3, 6, 8]
num_list.reverse()
# 结果:[8, 6, 3, 2, 5, 1]
print(num_list)
```
1. 语法
``` python
列表序列.sort( key=None, reverse=False)
```
> 注意:reverse表示排序规则,**reverse = True** 降序, **reverse = False** 升序(默认)
2. 快速体验
``` python
num_list = [1, 5, 2, 3, 6, 8]
num_list.sort()
# 结果:[1, 2, 3, 5, 6, 8]
print(num_list)
```
``` python
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘]
name_li2 = name_list.copy()
# 结果:[‘Tom‘, ‘Lily‘, ‘Rose‘]
print(name_li2)
- 代码
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘] i = 0 while i < len(name_list): print(name_list[i]) i += 1
- 代码
name_list = [‘Tom‘, ‘Lily‘, ‘Rose‘] for i in name_list: print(i)
原文:https://www.cnblogs.com/liuxuelin/p/14152220.html