列表和c中的数组很像,但是list可以存储不同类型的数据
创建
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
['鲁班', 'xiaoming', 1024]
<class 'list'>
访问
用索引进行访问
print(name_list[0])
for name in name_list:
print(name)
鲁班
鲁班
xiaoming
1024
更新
添加
- append:在列表末尾插入元素
str = 'lingyu'
name_list.append(str)
print(name_list)
list1 = []
for i in range(10):
list1.append(i)
print(list1)
['鲁班', 'xiaoming', 1024, 'lingyu']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- insert:在指定位置index前插入元素object
a = [0,1,2]
a.insert(1,'j')
print(a)
[0, 'j', 1, 2]
- extend:可以将另外一个集合里的元素添加到列表中
a = [1,2]
b = [3,4]
a.append(b)
print(a)
a.extend(b)
print(a)
[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]
修改
- 用索引直接修改
name_list[1] = '小明'
print(name_list)
['鲁班', '小明', 1024]
删除
- del:可以根据索引删除列表中某个元素,也可以直接删除列表,列表将会不存在
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
del name_list[0]
print(name_list)
del name_list
print(name_list)
['鲁班', 'xiaoming', 1024]
<class 'list'>
['xiaoming', 1024]
name 'name_list' is not defined
- pop:删除最后一个元素
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
name_list.pop()
print(name_list)
['鲁班', 'xiaoming', 1024]
<class 'list'>
['鲁班', 'xiaoming']
- remove:根据元素的值进行删除
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
name_list.remove('xiaoming')
print(name_list)
['鲁班', 'xiaoming', 1024]
<class 'list'>
['鲁班', 1024]
查找
- in,not in
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
findName = '小明'
if findName in name_list:
print('小明在列表中')
else:
print('不在')
['鲁班', 'xiaoming', 1024]
<class 'list'>
不在
排序
排序有sort和sorted两种方法,它们有一下两种区别:
- .sort对原列表进行了修改排序,sorted创建了新列表
- .sort属于列表的成员方法,sorted是对所有可迭代对象操作
from random import randint
num_list = []
for i in range(10):
num_list.append((randint(1,20)))
print(num_list)
num_list.sort()
print(num_list)
num_list.sort(reverse=True)
print(num_list)
new_list = sorted(num_list)
print(num_list)
print(new_list)
[6, 16, 4, 15, 13, 19, 20, 16, 7, 5]
[4, 5, 6, 7, 13, 15, 16, 16, 19, 20]
[20, 19, 16, 16, 15, 13, 7, 6, 5, 4]
[20, 19, 16, 16, 15, 13, 7, 6, 5, 4]
[4, 5, 6, 7, 13, 15, 16, 16, 19, 20]
嵌套
列表的成员可以是列表,相当于多维数组,这里以二维列表举例
school_name = [['qinghua','beida'],['nankai','tianda'],['dongqin','yanda']]
print(school_name)
print(school_name[0][1])
[['qinghua', 'beida'], ['nankai', 'tianda'], ['dongqin', 'yanda']]
beida
列表推导式,用于轻量级的循环创建
from random import randint
l = [randint(-10,10) for _ in range(10)]
print(l)
res2 = [x for x in l if x>=0]
print('使用列表解析筛选',res2)
[10, -1, -8, -4, -2, 7, 2, -8, -3, 7]
使用列表解析筛选 [10, 7, 2, 7]
网友评论