Python__11–列表

1 列表的定义

所谓列表就好像是把一堆数据放在一种特定的容器中,这个容器就称为列表,每个数据叫做元素 ,每个元素都有一个索引来表示它在列表中的位置。 在Python中列表的定义如下:列表是内置有序、可变序列,列表的所有元素放在一对中括号“[]”中,并使用逗号分隔开。

2 列表的创建

lst=[‘hello’,’world’,98]

lst=list([‘hello’,’world’,98])

列表生成式

lst=[i for i in range(1,10)]

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

测试代码:

lst=[‘hello’,’world’,98]print(lst)lst=list([‘hello’,’world’,98])print(lst)lst=[i**6 for i in range(1,10)]print(lst)print(lst[-5])

测试结果:

内存图(注意观察id),列表中存的是元素的id,通过id定位到元素的全部内容:

3 列表的特点

索引有顺序

左至右0,1,2,3……右至左-1,-2,-3……一个索引映射唯一一个数据,一个数据对两个索引(正数和负数的索引)。

可以包含多类型、数据可重复

测试代码:

lst = [1,2,3,4,5]print(lst[-5])print(lst[0])

测试结果:

一个数据对两个索引

4 列表元素的查询

测试代码:

lst=[‘hello’,’world’,98,’hello’]print(lst.index(‘hello’))print(lst.index(‘hello’,1,4))

测试结果:

print(lst.index(‘hello’))输出0,有重复数据,输出第一个print(lst.index(‘hello’,1,4))输出3,在索引1、2、3中查找。

获取单个元素

lst[0],0~N-1lst[-1],-N~-1

获取多个元素

lst[start:stop:step],不包括stop(前闭后开)

step为正数,从start开始往后计算切片

start省略,从0开始stop省略,到最后一个step省略,为1。如:[::1],[:2:1],[1:5]

step为负数,从start开始往前计算切片,倒序输出。lst[7:0:-1]

切片的第一个元素默认是列表的最后一个元素,切片的最后一个元素默认是列表的第一个元素

列表元素是否存在

in、not

print(10 in lst)print(10 not in lst)

列表的遍历

for item in lstprint(item) 离开你的那一天开始,左心房渐渐停止跳动…

Python__11–列表

相关文章:

你感兴趣的文章:

标签云: