社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

CAD小姐姐学Python,学习笔记第三篇,列表的使用

蚂蚁学Python • 4 年前 • 622 次点击  

今天的学习笔记是关于列表的,列表是Python中最基本数据结构,也是比较常用的Python数据类型,列表是一个数据的集合,集合内可以放任何数据类型,可以对序列执行增、删、改操作,对象地址不发生更改。下面就让我们学习下关于列表及相关应用吧。

列表

变量可以存储一个元素,而列表是一个大“容器”,可以存储N多个元素,程序可以方便地对这些数据进行整体操作

列表相当于其它语言中的数组

列表的创建

1.列表需要使用中括号[],元素之间使用英文的逗号进行分隔

2.调用内置函数list()

列表的特点

1.列表元素按顺序有序排列

2.索引映射唯一一个数据

3.列表可以存储重复数据

4.任意数据类型混合

3.根据需要动态分配和回收内存

列表的查询操作

1.获取列表中指定元素的索引   index():

1.如果列表中存在N个相同元素,只返回相同元素中的第一个元素的索引

2.如果查询的元素在列表中不存在,则会抛出ValueError

3.还可以在制定的start和stop之间进行查找

例1:

lst=['hello','python','98','hello']
print(lst.index('hello'))
0

例2:

lst=(['hello','python','world'])
print(lst.index('Baby'))
---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_13648/1175636271.py in
1 lst=(['hello','python','world'])
----> 2 print(lst.index('Baby'))


ValueError: 'Baby' is not in list

例3:

lst=['hello','python','98','hello']
print(lst.index('hello',1,4))
3
2.获取列表中的单个元素
 1.正向索引从0到N-1,举例:lst[0]

2.逆向索引从-N到-1,举例:lst[-N]

3.指定索引不存,抛出indexError
lst=['hello','world',98,'hello','world',234]
print(lst[2])            #获取索引为2的元素
98
lst=['hello','world',98,'hello','world',234]
print(lst[-3])            #获取索引为-3的元素
hello
lst=['hello','world',98,'hello','world',234]
print(lst[6])            #获取索引为6的元素,指定索引不在,报错
---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_13648/2375259125.py in
1 lst=['hello','world',98,'hello','world',234]
----> 2 print(lst[6]) #获取索引为6的元素


IndexError: list index out of range
3.获取列表中的多个元素

语法格式:

列表名[start:stop:step]

切片操作:1.切片的结果(原列表片段的拷贝)

      2.切片的范围 [start,stop)

3.step默认为1(简写为[start:stop]

4.step为正数:[:stop:step] 切片的第一个元素默认是列表的第一个元素 (从start开始往后计算切片)

[start::step] 切片的最后一个元素默认是列表的最后一个元素

5.step为负数 [:stop:step] 切片的第一个元素默认是列表的最后一个元素(从start开始往前计算切片)

[start::step] 切片的最后一个元素默认是列表的第一个元素

例:切片的范围、切片的结果

lst=[10,20,30,40,50,60,70,80]
print('原列表',(lst))
lst2=lst[1:6:1]                #start=1,stop=6,step1
print('切的片段:',(lst2))
原列表 [10, 20, 30, 40, 50, 60, 70, 80]
[20, 30, 40, 50, 60]
切的片段: [20, 30, 40, 50, 60]

例:step默认为1

lst=[10,20,30,40,50,60,70,80]
print(lst[1:6:1])    #start=1,stop=6,step1
print(lst[1:6])      #start=1,stop=6,默认步长为1
print(lst[1:6:])     #start=1,stop=6,默认步长为1
[20, 30, 40, 50, 60]
[20, 30, 40, 50, 60]
[20, 30, 40, 50, 60]

例:step为正数

lst=[10,20,30,40,50,60,70,80]
print(lst[1:6:2])     #start=1,stop=6,step2
print(lst[:6:2])      #start从最初开始,stop=6,step2
print(lst[1::2])      #start=1,stop到最后,默认步长为1
[20, 40, 60]
[10, 30, 50]
[20, 40, 60, 80]

例:step为负数

lst=[10,20


    
,30,40,50,60,70,80]
print('原列表',lst)
print(lst[::-1])      #start=7(最后一个),stop=0,step = -1
print(lst[7::-1])      #start=7,stop=0,step = -1
print(lst[6:0:-2])      #start=6,stop到最后不包括0,step = -2
原列表 [10, 20, 30, 40, 50, 60, 70, 80]
[80, 70, 60, 50, 40, 30, 20, 10]
[80, 70, 60, 50, 40, 30, 20, 10]
[70, 50, 30]
4.判断指定元素在列表中是否存在

1.判断指定定元素在列表中是否存在

元素 in 列表名

元素 not in 列表名

2.列表元素的遍历

for 迭代变量 in 列表名:

操作

例1:

lst=[10,20,'python','hello']
print(10 in lst)
print(100 in lst)
print(10 not in lst)
print(100 not in lst)
True
False
False
True

例2:

lst=[10,20,'python','hello']
for item in lst:
    print(item)
10
20
python
hello
5.列表元素的增加

操作方法:

append() :在列表的末尾添加一个元素

extend() :在列表的末尾至少添加一个元素

insert() :在列表的任意位置添加一个元素

切片 :在列表的任意位置添加至少一个元素

例:向列表的末尾添加一个元素

lst=[10,20,30]
print('添加元素前',lst)
lst.append(40)
print('添加元素后',lst)
print('添加元素前',lst,id(lst))
print('添加元素后',lst,id(lst))  id 相同说明还是同一个列表,只是在末尾增加了一个元素
添加元素前 [10, 20, 30]
添加元素后 [10, 20, 30, 40]
添加元素前 [10, 20, 30, 40] 2418471799232
添加元素后 [10, 20, 30, 40] 2418471799232

例:向列表的末尾至少添加一个元素

lst=[10,20,30]
lst2=['hello','python']
lst.append(lst2)         #将lst2作为一个元素添加到lst末尾
print(lst)                        
[10, 20, 30, ['hello', 'python']]
lst=[10,20,30]
lst2=['hello','python']
lst.extend(lst2)         #将lst2的每个元素添加到lst末尾,向列表的末尾添加多个元素
print(lst)      
[10, 20, 30, 'hello', 'python']

例3:在列表指定的位置添加元素

lst=[10,20,30]
lst.insert(1,40)     #在索引为1的位置添加40
print(lst)
[10, 40, 20, 30]

例4:切片然后在任意位置添加N多个元素

lst=[10,20,30]
lst3=[True,False,'hello']
lst[1:]=lst3            #从索引为1的位置开始到最后切片并替换添加新元素
print(lst)
[10, True, False, 'hello']
6.列表元素的删除

操作方法:

1.remove() :一次删除一个元素

重复元素只删除第一个

元素不存在抛出ValueError

2.pop() :删除一个指定索引位置上的元素

指定索引不存在抛出IndexError

不指定索引,删除列表中最后一个元素

3.切片 :一次至少删除一个元素

4.clear :清空列表

5.del :删除列表

例1:remove()

lst=[10,20,30,40,50,30]
lst.remove(30)
print(lst)                   #从列表中移除一个元素,如果有重复元素只移除第一个元素
lst.remove(100)              #报错元素不存在
[10, 20, 40, 50, 30]



---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_8992/2932006073.py in
2 lst.remove(30)
3 print(lst) #从列表中移除一个元素,如果有重复元素只移除第一个元素
----> 4 lst.remove(100)


ValueError: list.remove(x): x not in list

例2:pop()

lst=[10,20,30,40,50,30]
lst.pop(1)                 #从列表中移除索引位置是1的元素 
print(lst)
lst.pop(7)                  #从列表中移除索引位置是7的元素,不存在7的元素报错异常
print(lst)
[10, 30, 40, 50, 30]



---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_12892/2040156885.py in
2 lst.pop(1) #从列表中移除索引位置是1的元素
3 print(lst)
----> 4 lst.pop(7) #从列表中移除索引位置是7的元素,不存在7的元素报错异常
5 print(lst)


IndexError: pop index out of range
lst=[10,20,30,40,50,30]
lst.pop()                  #不指定索引,删除列表中最后一个元素
print(lst)
[10, 20, 30, 40, 50]

例3:切片

lst=[10,20,30


    
,40,50,30]
new_list=lst[1:3]              #切片操作删除至少一个元素,将产生一个新的列表对象
print('原列表',lst)
print('切片后的列表',new_list)
原列表 [10, 20, 30, 40, 50, 30]
切片后的列表 [20, 30]
lst=[10,20,30,40,50,30]
lst[1:3]=[]              #切片操作删除原列表中的内容,不产生新的列表,把索引的1和2的元素删除
print(lst)
[10, 40, 50, 30]

例4:clear

lst=[10,20,30,40,50,30]
lst.clear()       #清除列表中的所有元素
print(lst)          
[]

例5:del

lst=[10,20,30,40,50,30]
del lst      #直接清除列表对象
print(lst)    #报错   'lst' is not defined    
---------------------------------------------------------------------------

NameError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_8992/1850059668.py in
1 lst=[10,20,30,40,50,30]
2 del lst
----> 3 print(lst)


NameError: name 'lst' is not defined
7.列表元素的修改操作

1.为指定索引的元素赋予一个新值

2.为指定的切片赋予一个新值

例1:

lst=[10,20,30,40]
lst[2]=100        #修改索引为2的元素换成100
print(lst)
[10, 20, 100, 40]

例2:

lst=[10,20,30,40]
lst[1:2]=[50,60,70,80]   #索引1和2的值换成50,60,70,80
print(lst)
[10, 50, 60, 70, 80, 30, 40]
8.列表元素的排序操作

1.调用sort()方法,列表中的所有元素默认按照从小到大的顺序进行排序,可以指定reverse=True,进行降序排序

2.调用内置函数sorted(),可以指定reverse=True,进行降序排序,原列表不发生改变,排序后产生一个新的列表对象

例1:sort(),对原列表进行排序

lst=[20,40,10,98


    
,54]
print('排序前的列表',lst,id(lst))  
lst.sort()                            #通过指定关键字参数,将列表中的元素进行升序排序
print('排序后的列表',lst,id(lst))     #id 相同说明原列表对象不变,只是做个排序处理
lst.sort(reverse=True)               #reverse=True 表示降序排列
print(lst)
lst.sort(reverse=False)               #reverse=False 表示降序排列
print(lst)
排序前的列表 [20, 40, 10, 98, 54] 2500174974080
排序后的列表 [10, 20, 40, 54, 98] 2500174974080
[98, 54, 40, 20, 10]
[10, 20, 40, 54, 98]

例2:sorted(),原列表不变,排序后产生一个新的列表对象

lst=[20,40,10,98,54]
print(lst)
new_list=sorted(lst)    #升序排序,排序后的是一个新的列表对象
print(new_list)
new_list=sorted(lst,reverse=True)   #降序排序,排序后是一个新的列表对象
print(new_list)
[20, 40, 10, 98, 54]
[10, 20, 40, 54, 98]
[98, 54, 40, 20, 10]
9.列表的复制
list.copy() :复制列表

例:

lst=[10,20,30,'Baby',50,30,60,30]
lst3=lst2=lst.copy()       #lst2和lst3复制lst列表
print(lst2)              
print(lst3)
[10, 20, 30, 'Baby', 50, 30, 60, 30]
[10, 20, 30, 'Baby', 50, 30, 60, 30]
10.列表生成式(生成列表的公式)
语法格式:

[i*i for i in range(1,10)]

i*i 表示列表元素

i 表示自定义变量

range() 可迭代对象

**注意事项:‘表示列表元素的表达式’中通常包含自定义变量

例:

lst=[i for i in range(1,10)]
print(lst)
lst2=[i*i for i in range(1,10)]
print(lst2)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81]

例:列表中的元素是2,4,6,8,10

lst=[i*2 for i in range(1,6)]
print(lst)
[2, 4, 6, 8, 10]


最后,推荐蚂蚁老师的Python入门课,限时249元:



Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/125067