blog/docs/code/python/list.md

212 lines
3.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: List 列表
date: 2020-07-22 22:29:24
tags: [Python]
categories: [Python]
author: Anges黎梦
---
## List 列表
> 序列是Python中最基本的数据结构。
> 序列中的每个元素都分配一个数字 - 它的位置或索引第一个索引是0第二个索引是1依此类推。
> Python有6个序列的内置类型但最常见的是列表和元组。
> 序列都可以进行的操作包括索引,切片,加,乘,检查成员。
## 创建列表
> 创建列表,只需要用逗号把元素分割开,用方括号括起来。
```
list_1 = ['abc', 'def', 'jkjl', 12121]
print(list_1)
```
执行结果:
```
['abc', 'def', 'jkjl', 12121]
```
## index取值
> 列表中[]的用法,与字符串中的用法一致
>
> [开始位置:结束位置:幅度]
```
print(list_1[0]) # 列表中的第一个元素
print(list_1[-1]) # 列表中最后一个元素
print(list_1[::2]) # 从0到2的元素前闭后开
```
执行结果:
```
abc
12121
['abc', 'jkjl']
```
## 更新列表
> append 在列表后,追加元素
```
list_2 = []
print(list_2)
list_2.append(111)
print(list_2)
list_2.append(222)
print(list_2)
list_2.append([1,2])
print(list_2)
# list_2[3] = 555 不可使用index方式添加新元素
list_2[2] = 555 # 可以使用index的方式更新元素
print(list_2)
```
执行结果:
```
[]
[111]
[111, 222]
[111, 222, [1, 2]]
[111, 222, 555]
```
## 删除列表中的元素
### del
```
del list_2
del list_2[0]
```
### remove
```
res = list_2.remove(111)
print(list_2)
print(res)
```
### pop
```
res = list_2.pop(0)
print(list_2)
print(res)
```
### remove与pop
- remove移除某一个元素传递参数填写的是value值
- pop移除列表中的某一个元素传递参数为list中的index序列号
如果不填写参数,那么则移除最后一个元素。
区别:
- remove方法没有返回值pop会返回它移除的那个元素值。
## 列表统计
> 下面三个函数,最大和最小两个函数,比对的列表中,所有元素应为同一类型
```
print(len(list_2)) # 长度
print(max(list_2)) # 最大值
print(min(list_2)) # 最小值
```
执行结果:
```
3
555
111
```
## 列表合并
```
print(list_1+list_2)
```
执行结果:
```
['abc', 'def', 'jkjl', 12121, 111, 222, 555]
```
## 重复
```
list_3 = list_2 * 3
print(list_3)
```
执行结果:
```
[111, 222, 555, 111, 222, 555, 111, 222, 555]
```
## 判断元素是否存在
```
print(111 in list_2)
```
执行结果:
```
True
```
## list 转换为列表
```
a = "['q','t','y']"
print(list(a)) # 字符串中的每一个元素,当作列表中的每一个元素
```
执行结果:
```
['[', "'", 'q', "'", ',', "'", 't', "'", ',', "'", 'y', "'", ']']
```
## count
> 统计元素在列表中出现的次数
```
print(list_3.count(111))
```
执行结果:
```
3
```
## extend
> 列表末尾,添加另一个序列中的多个值
```
list_3.extend(list_1)
print(list_3)
```
执行结果:
```
[111, 222, 555, 111, 222, 555, 111, 222, 555, 'abc', 'def', 'jkjl', 12121]
```
## index
> 是在列表中找到第一个与搜索值相同的值的index并返回index
```
print(list_2.index(111))
print(list_3.index(111))
```
执行结果:
```
0
0
```
## insert
```
list_2.insert(2, 888)
print(list_2)
```
执行结果:
```
[111, 222, 888, 555]
```
## sort reverse
```
list_2.sort(reverse=False) # False为从小到大True为从大到小
print(list_2)
list_2.reverse() # 从大到小排序
print(list_2)
list_1.reverse()
print(list_1)
```
执行结果:
```
[111, 222, 555, 888]
[888, 555, 222, 111]
[12121, 'jkjl', 'def', 'abc']
```