Python中的list是一种有序的可变集合,可以包含任意类型的元素,使用方括号[]来表示。以下是list的常见用法:
1. 创建list
```
# 创建一个空的list
my_list = []
# 创建一个包含元素的list
my_list = [1, 2, 3, "hello", "world"]
```
2. 访问list元素
```
# 通过下标访问list元素
my_list = [1, 2, 3, "hello", "world"]
print(my_list[0]) # 输出1
print(my_list[3]) # 输出"hello"
# 通过负数下标访问list元素,负数下标表示从右向左数
my_list = [1, 2, 3, "hello", "world"]
print(my_list[-1]) # 输出"world"
print(my_list[-2]) # 输出"hello"
```
3. 修改list元素
```
# 通过下标修改list元素
my_list = [1, 2, 3, "hello", "world"]
my_list[0] = 0
my_list[3] = "hi"
print(my_list) # 输出[0, 2, 3, "hi", "world"]
```
4. 添加元素到list
```
# 添加元素到list末尾
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出[1, 2, 3, 4]
# 插入元素到指定位置
my_list = [1, 2, 3]
my_list.insert(1, "hello")
print(my_list) # 输出[1, "hello", 2, 3]
```
5. 删除list元素
```
# 删除list中指定元素
my_list = [1, 2, 3, "hello", "world"]
my_list.remove(3)
my_list.remove("hello")
print(my_list) # 输出[1, 2, "world"]
# 删除list末尾元素
my_list = [1, 2, 3, "hello", "world"]
my_list.pop()
print(my_list) # 输出[1, 2, 3, "hello"]
```
6. 切片操作
```
# 切片操作,获取list的一部分
my_list = [1, 2, 3, "hello", "world"]
print(my_list[1:3]) # 输出[2, 3]
print(my_list[:3]) # 输出[1, 2, 3]
print(my_list[3:]) # 输出["hello", "world"]
print(my_list[::2]) # 输出[1, 3, "world"]
```
7. 迭代list
```
# 迭代list
my_list = [1, 2, 3, "hello", "world"]
for item in my_list:
print(item)
# 输出:
# 1
# 2
# 3
# hello
# world
```
8. 获取list长度
```
# 获取list长度
my_list = [1, 2, 3, "hello", "world"]
print(len(my_list)) # 输出5
```
9. 判断元素是否在list中
```
# 判断元素是否在list中
my_list = [1, 2, 3, "hello", "world"]
print(3 in my_list) # 输出True
print("hi" in my_list) # 输出False
```
10. list排序
```
# list排序
my_list = [3, 2, 1, 5, 4]
my_list.sort()
print(my_list) # 输出[1, 2, 3, 4, 5]
```
11. 复制list
```
# 复制list
my_list = [1, 2, 3, "hello", "world"]
new_list = my_list.copy()
print(new_list) # 输出[1, 2, 3, "hello", "world"]
```
以上是list的基本用法,list还有很多其他的用法,可以根据需要进行查阅。