Python列表(Lists)

Python列表(Lists) 首页 / 数据结构入门教程 / Python列表(Lists)

Lists是Python中最通用的数据类型,可以写成方括号之间用逗号分隔的值(元素)的列表,关于列表的重要一点是列表中的元素不必是同一类型。

创建列表就像在方括号之间放置不同的逗号分隔值一样简单。例如-

list1=['physics', 'chemistry', 1997, 2000]
list2=[1, 2, 3, 4, 5 ]
list3=["a", "b", "c", "d"]

与字符串索引类似,列表索引从0开始,列表可以被切片,连接等。

访问列表元素

要访问列表中的值,请使用方括号对一个或多个索引进行切片,以获取该索引处可用的值。

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-lists-data-structure.html

来源:LearnFk无涯教程网

#!/usr/bin/python

list1=['physics', 'chemistry', 1997, 2000]
list2=[1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

执行以上代码后,将产生以下输出-

无涯教程网

list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]

更新列表元素

您可以通过在赋值运算符的左侧提供切片来更新列表的单个或多个元素,并可以使用append()方法将其添加到列表中的元素。例如-

#!/usr/bin/python

list=['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : "
print list[2]
list[2]=2001
print "New value available at index 2 : "
print list[2]

执行以上代码后,将产生以下输出-

无涯教程网

Value available at index 2 :
1997
New value available at index 2 :
2001

删除列表元素

要删除列表元素,可以使用del语句(如果您确切知道要删除的元素)或使用remove()方法。例如-

#!/usr/bin/python

list1=['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print "After deleting value at index 2 : "
print list1

执行以上代码后,将产生以下输出-

无涯教程网

['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

AI绘画核心技术与实战 -〔南柯〕

深入浅出可观测性 -〔翁一磊〕

自动化测试高手课 -〔柳胜〕

To B市场品牌实战课 -〔曹林〕

微信小程序全栈开发实战 -〔李艺〕

移动端自动化测试实战 -〔思寒〕

ZooKeeper实战与源码剖析 -〔么敬国〕

从0开始做增长 -〔刘津〕

AI技术内参 -〔洪亮劼〕

好记忆不如烂笔头。留下您的足迹吧 :)