python数据类型-列表

1 python中列表的定义

python中列表是一种有序和可更改的集合,允许重复的成员,列表中的元素之间数据类型可以不同(元素之间数据类型可以不相同,这一点和其它的面向对象的开发语言有很大的不同,如C#、Java)。

2 创建列表的两种方式

2.1 通过方括号 []

python 复制代码
empty_list = []         # 创建一个空列表
lst = [1, '2', True, [1, 2]]    # 创建一个非空列表

2.2 通过内置函数list()

list()函数创建列表时,注意使用双括号。使用list函数也可以将字符串、元组、字典和集合转换为列表。

python 复制代码
shuiguo = list(('apple', 'banana', 'cherry'))
print(shuiguo, type(shuiguo)) # ['apple', 'banana', 'cherry'] <class 'list'>
python 复制代码
str = 'henry_hu'
str_list = list((str))
print(str_list) # ['h', 'e', 'n', 'r', 'y', '_', 'h', 'u']

3 列表基本操作--增、删、改、查

3.1 增,即为列表添加新元素

通过**append()**函数,为列表增加元素

python 复制代码
empty_list = []  # 创建一个空列表
empty_list.append(1)
print(empty_list) # [1]

当需要在特定位置插入元素时,用 **insert()**函数,insert函数需传入两个参数,第一个即要插入的位置,第二个参数为想要插入的值

python 复制代码
empty_list = [] 
empty_list.append(1)
empty_list.insert(0, 'henry')
print(empty_list)  # ['henry', 1]

3.2 删

remove() : 删除指定值的项目,语法 mylist.remove(值)

pop():删除制定索引的项目,若未传入索引,则删除列表最后一个项目,语法 mylist.pop(1)

clear():清空列表,语法 mylist.clear()

del :关键字删除指定的索引,如 del mylist[0]

python 复制代码
mylist = [1, 2, 3, 1, 4, 5, 'henry']
mylist.remove(1)
print(mylist)  # [2, 3, 1, 4, 5, 'henry']
mylist.pop(0)
print(mylist)  # [3, 1, 4, 5, 'henry']
del mylist[0]
print(mylist)  # [1, 4, 5, 'henry']
mylist.clear()
print(mylist) # []

3.3 改

通过索引修改列表的值

python 复制代码
mylist = [1, 2, 3, 1, 4, 5, 'henry']
mylist[0] = 'Tom'
print(mylist)  # ['Tom', 2, 3, 1, 4, 5, 'henry']

3.4 查-查询、访问

1)通过索引,访问特定位置上的元素,语法:mylist[index],注意第一个元素的索引时0,-1代表最后一个元素

2)通过切片,访问某一段元素,语法:mylist[startIndex:length]

第一个参数:访问的起始位置,第二个参数:索引的终止位置

mylist[2,5]:代表截取 索引为 2 3 4 5 共四个元素

  1. 循环访问
python 复制代码
mylist = [1, 2, 3, 1, 4, 5, 'henry']

print(mylist[0])  # 1

print(mylist[-1])  # henry

print(mylist[2:5])  # [3, 1, 4]

for item in mylist:
    print(item)

其它内置函数

相关推荐
Accelemate几秒前
[故障复盘] PyCharm 远程开发:中文文件名“隐身”与无法创建文件的排查
ide·python·pycharm
CodeCraft Studio1 分钟前
国产化Excel开发组件Spire.XLS教程:以Python编程方式在Excel中高亮重复值
开发语言·python·excel·spire.xls·excel自动化·excel高亮重复值·python处理excel
轻竹办公PPT2 分钟前
电商运营做年度复盘PPT?2025工具评测榜单
python·powerpoint
Q_Q5110082855 分钟前
python_django基于大数据技术旅游景点数据分析推荐系统现_wrqk1aes
大数据·python·django
小鸡吃米…10 分钟前
Python - 命令行参数
开发语言·python
子午14 分钟前
【蔬菜识别系统】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积网络+resnet50算法
人工智能·python·深度学习·蔬菜识别
哦哦3312 小时前
线性回归和回归决策树(CART)对比
python·pycharm
qq7422349842 小时前
VitePress静态网站从零搭建到GitHub Pages部署一站式指南和DeepWiki:AI 驱动的下一代代码知识平台
人工智能·python·vue·github·vitepress·wiki
陈天伟教授8 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
2301_764441339 小时前
Aella Science Dataset Explorer 部署教程笔记
笔记·python·全文检索