0
点赞
收藏
分享

微信扫一扫

python(8)--列表·初阶使用


目录

​​一、认识列表​​

​​二、列表的基本定义​​

​​三、读取列表元素​​

​​四、列表切片​​

​​五、列表相关简单函数​​

​​六、替换列表元素​​

​​七、列表相加 ​​

​​八、删除列表​​

​​九、列表·进阶使用​​

​​参考资料​​

一、认识列表

列表( list )是 Python 的一种可以更改内容的数据类型,它是由一系列元素所组成的序列。
其实在其他程序语言,相类似的功能是称数组。不过, Python 的列表功能除了可以存储相同数据类型,例如,整数、浮点数、字符串,也可以存储不同数据类型,例如,列表内同时含有整数、浮点数和字符串。甚至一个列表也可以内含其他列表或是字典。

二、列表的基本定义

语法格式:list_name=[元素1,……,元素n]

实例:

score=[100,99,67,88,65]

score=['lihua',100,99,67,88,65]

name=['lihua','zhangsan','lisi']

name=['李华‘,‘张三’,’李四‘]

score=[100,99,67,88,65]
print(score)
score=['lihua',100,99,67,88,65]
print("lihua的成绩:",score)
name=['lihua','zhangsan','lisi']
print(name)
name=['李华','张三','李四']
print(name)

 

python(8)--列表·初阶使用_python

 三、读取列表元素

第一个元素,索引值为零,第二个元素是1,以此类推:

a=[a(0),a(1),a(2),a(3),a(4),……,a(n)]

 将学科和成绩对应起来:

score=[100,99,67,88,65]
print("数学",score[0])
print("英语",score[1])
print("化学",score[2])
print("生物",score[3])
print("物理",score[4])

 

python(8)--列表·初阶使用_数据类型_02

 四、列表切片

基本概念:在设计程序时,常会需要取得列表前几个元素、后几个元素、某区间元素或是依照一定规则排序的元素,所取得的系列元素也可称子列表,这个观念称列表切片( list slices )。

list[start:end]              #读取从索引start到end-1的元素

list[:n]                          #读取列表前n个元素

list[n:]                          #取得列表索引n到最后

list[-n:]                        #取得列表后n个元素

list[start:end:step]    #每隔step大小的区间后,再读取索引start到end-1的元素

list[-1]                        #最后一个元素

list[:]                          #取得全部的元素

score=[100,99,67,88,65]
print("前三个元素",score[0:3])
print("中间三个元素",score[1:4])
print("打印奇数位的元素",score[0:6:2])
print("前三个元素:",score[:3])
print("后三个元素",score[-3:])
print("打印第三个元素到最后:",score[2:])

 

python(8)--列表·初阶使用_pycharm_03

 五、列表相关简单函数

最大值:  max()

最小值:  min()

求和:      num()

列表个数: len()

score=[100,99,67,88,65]
print("列表的个数",len(score))
print("最小值",min(score))
print("最大值",max(score))
print("总和:",sum(score))
print("后四个元素的和",sum(score[1:5]))

 

python(8)--列表·初阶使用_pycharm_04

 六、替换列表元素

替换索引为0的元素:100->120

score=[100,99,67,88,65]
print(score)
score[0]=120
print(score)

 

python(8)--列表·初阶使用_pycharm_05

七、列表相加 

列表相加:

total=[]
score=[100,99,67,88,65]
name=["A","B","C"]
total=score+name
print(total)

python(8)--列表·初阶使用_pycharm_06

 列表元素相加:

score=[100,99,67,88,65]
name=["A","B","C"]
total=name[0] + ":"+str(score[0])
print("元素相加:",total)

python(8)--列表·初阶使用_pycharm_07

八、删除列表

del list_name               #删除叫做list_name的列表

del list_name[i]            #删除索引为i的元素

del list_name[start:end]        #删除索引start到end-1的元素

del liat_name[start:end:step]         #每隔step,删除索引start到end-1索引的元素

score=[1,2,3,4,5,6,7]
del score[6]
print(score)
del score[0:1]
print(score)
del score[0:4:2]
print(score)

 

python(8)--列表·初阶使用_pycharm_08

删除列表:

score=[1,2,3,4,5,6,7]
del score
print(score)

 

python(8)--列表·初阶使用_Python_09

name 'score' is not defind

九、列表·进阶使用

​​Python(9)--列表·进阶使用_码银的博客-

参考资料

《Python 王者归来》   洪锦魁著

本博客是纯粹个人学习,与朋友交流共赏,不存在任何商业目的。

如果您对此文章及作品版权的归属存有异议,请立即通知我,我将在第一时间予以删除,同时向你表示歉意!

举报

相关推荐

0 条评论