前言
python中的list是很常用的结构,顾名思义,list就是用来保存一组东西。这些东西可以是不同的类型。看下面的例子。
创建list
Bash
# 空list
my_list = []
# int list
my_list = [1, 2, 3]
# 混合类型的list
my_list = [1, "Hello", 3.4]
# list中带list
my_list = ["mouse", [8, 4, 6], ['a']]
- 创建list使用[]即可,在其中写入值,这些值就会保存在列表中
- list中可以混合保存不同类型的东西,甚至于可以保存另一个list
访问list
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
n_list = ["Happy", [2,0,1,5]]
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
- 通过索引即可获得list中的元素
- 注意索引是从0开始计算,也就是说要获取第1个元素,则索引为0
我们还可以通过负数索引来反向指定元素
Bash
my_list = ['p','r','o','b','e']
# 倒数第1个,即最后一个元素
# Output: e
print(my_list[-1])
# 倒数第5个
# Output: p
print(my_list[-5])
切片获取
刚刚我们只能一次获取一个元素,我们可以通过切片来一次获取一段范围的元素出来。当然,获取的结果也是list
Bash
my_list = ['p','r','o','g','r','a','m','i','z']
# 从第3个元素开始,取到第5个为止(第5个元素不取)
print(my_list[2:5])
# 从头开始,取到第5个
print(my_list[:-5])
# 从第5个开始,取到结尾(结尾也在结果中)
print(my_list[5:])
# 从头取到尾,相当于把list复制一次
print(my_list[:])
输出:
Bash
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
- 在[]之间使用start:end指定范围
- 范围的end是不会出现在结果中
- 可以不指定start或end,不指定就是代表list的开始位置和结束位置
修改list
直接使用等号赋值的方式即可修改list中元素的值
odd = [2, 4, 6, 8]
# 把第一个元素改为1
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# 把1到3的元素,一次替换
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
输出:
Bash
[1, 4, 6, 8]
[1, 3, 5, 7]
通过list的方法可以添加元素
Bash
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
输出:
Bash
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
- append()方法用于每次添加一个元素
- extend()方法用于每次添加一个list的元素
使用del可以移除某个元素
Bash
other_list=my_list = ['p','r','o','b','l','e','m']
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# 一次移除一个范围的元素
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# 注意,这里实际是把变量my_list移除了,而不是把列表清空。
# 实际的列表还在,比如我们是可以通过other_list访问
del my_list
# 这里无法访问这个变量了,会报错
print(my_list)
输出:
Bash
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-67ac42c98786> in <module>
17
18 # 这里无法访问这个变量了,会报错
---> 19 print(my_list)
20
21 # 这次是清空了list
NameError: name 'my_list' is not defined
使用clear()方法清空list
Bash
# 这次是清空了list
other_list.clear()
# Output: []
print(other_list)
列表推导式
python中可以用推导式快速处理一个list,以一个新的list作为处理结果输出
Bash
my_list = [3, 8, 1, 6, 0, 8, 4]
# 把偶数的元素提取出来,平方运算后输出到新list
res_list=[n**2 for n in my_list
if n%2==0]
# Output: [64, 36, 0, 64, 16]
print(res_list)
输出:
Bash
[64, 36, 0, 64, 16]
- 推导式可用于生成多种数据结构
- 推导式比普通遍历,性能高很多,特别数据量大的情况下会越加明显
推导式不是本文重点,以后会有单独的文章详细介绍推导式
判断是否包含某个元素
Bash
my_list = ['p','r','o','b','l','e','m']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
输出:
Bash
True
False
True
最后
list是python中最常用的数据结构之一,当你需要保存一组值,并且这些值和数量都是在脚本运行的过程才知道,那么list是一个很好的选择。本文只介绍了list常用的一些方法,对于入门来说已经足够,以后会有相关高级用法的文章,敬请关注。