栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

列表生成式python(python中列表的特点)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

列表生成式python(python中列表的特点)

列表与变量的区别

变量可以存储一个元素,而列表是一个“大容器”可以存储N多个元素,程序可以方便地对这些数据进行整体操作。列表相当于其他语言中的数组
例:

a=10#变量存储的是一个对象的引用
print(id(a))
print(type(a))
print(a)    #变量的id、类型、值
lst=['hello','world',98]
print(id(lst))
print(type(lst))
print(lst)   #列表的id、类型、值

结果;

140704105957312

10
3147505991808

[‘hello’, ‘world’, 98]

列表的创建

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

创建方式一:只使用中括号(其中lst只是变量名,可以随意命名)

lst=[’ ‘,’ ']

创建方式二:使用内置函数list()lst1=list([’ ‘,’ '])

例如:

a=['hello','world',98] #第一种创建方式
lst1=list(['hello','world',98])#第二种创建方式
print(a)
print(lst1)

结果:

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

列表的特点

列表元素按顺序有序排列索引映射唯一数据列表可以存储重复数据任意数据类型混存根据需要动态分配和回收内存
例:

lst=['hello','world',98]
print(lst)#列表元素按顺序有序排列
lst=['hello','world',98]
print(lst[0])#索引映射唯一数据,从前往后索引是从0开始。
print(lst[-1])#从后往前索引最后面的是-1,倒数第二个为-2,以此类推

lst=['hello','hello',98]#列表可以存储重复数据
print(lst)

结果:

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

其中索引映射唯一数据,从前往后索引是从0开始,从后往前是从-1开始,如图所示:

列表的查询操作

一、获取列表中指定元素的索引使用index()函数

index()函数:

如查找列表中存在N个相同元素,只返回相同元素的第一个索引的序列

例:

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

结果:

0

如果查找的元素在列表中不存在,则会抛出ValueError的错误提示

例:

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

结果:

ValueError: ‘python’ is not in list

可以在指定的start和stop之间进行查找

例:

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

结果:

3

注意:列表中索引的第一个元素是从0开始的

二、获取列表中的多个元素
语法格式:

列表名[start:stop:step]

切片操作(见图)

例:

lst=[10,20,30,40,50,60,70,80]
print(lst[1:6:1])
print(lst[::-1])#step为负数,逆序输出
print(lst[:-5:-2])#step为负数时,切片的最后一个元素默认为列表的第一个元素

结果:

[20, 30, 40, 50, 60]
[80, 70, 60, 50, 40, 30, 20, 10]
[80, 60]

判断指定元素在列表中是否存在,用in和not in
格式:

元素 in 列表名
元素 not in 列表名

例:

lst=[10,20,'python','hello']
print(10 in lst)
print(30 in lst)
print(30 not in lst)
print('python' in lst)

结果:

True
False
True
True

列表元素的遍历:

格式:

for 迭代变量 in 列表名:
操作

例:

lst=[10,20,'python','hello']
for item in lst:
    print(item)

结果:

10
20
python
hello

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/772430.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号