Python从0到1——③列表(list) 操作

本文详细介绍了Python编程中列表(list)的基础结构和操作,包括基础操作和核心操作,帮助初学者从0开始掌握列表的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python从0到1——列表(list) 操作

其他常用操作见:Python从0到1_python 把0到1等分为1000个元素-优快云博客

目录

一、List基础结构

二、List基础操作

三、List核心操作


一、List基础结构

# list基础结构
    # 创建list结构
temp = []
print(type(temp))
    # list 可以存储任何类型的对象,没有长度限制
print([1,2,3,4])
print(['1','2','3','4'])
print([1,True,'3',4.0])

二、List基础操作

# list 基础操作
temp = [1,True,'3',4.0]
temp2 = [1, 1,'3',2]
    # 1.长度
print(len(temp))
    # 2.加法
print(temp + temp2)
    # 3.乘法
print(temp * 2)
    # 4.索引
print(temp[0])
print(temp[1])
print(temp[0:])     # 从0开始全部的元素
    # 5.根据索引替换元素
temp[0:1] = ['hello', 'world']  # 从索引0到索引1的元素
print(temp)
    # 6.删除元素
temp = [1,2,3,4,5,6,7,8,9,0]
print(temp)
del temp[1:3]       # 索引3不会被删掉,只删索引1、2
print(temp)
    # 7.判断元素是否在list中
print(1 in temp)
print(2 in temp)
print(10 not in temp)
print(9 not in temp)

三、List核心操作

# list 核心操作
    # 1.list中嵌套list
temp = [1, 2, [3, 4]]
print(temp)
print(temp[2])
print(temp[2][1])
    # 2.计数操作
temp = ['apple','apple','apple','banana','banana','banana','apple']
print(temp.count('apple'))
    # 3.定位元素的索引(如果list有多个该元素,则返回第一个)
print(temp.index('apple'))
    # 4.尾部追加元素(每次只能添加一个元素)
temp = [1,2,3]
temp.append(4)
temp.append(4)
print(temp)
    # 5.插入元素(新的元素会出现在位置2,其他元素向后移动)
temp.insert(2,'python')
print(temp)
    # 6.删除元素(之前已经给出了del的删除方法)
temp = [1,2,3,4,5,6,7]
del temp[1]     # del是根据下标删除元素
print(temp)
temp = [1,2,3,4,5,6,7,1]
temp.remove(2)  # remove是根据元素值删除元素
print(temp)
temp.remove(1)      # 如果有重复的数值,默认只删除最靠前的元素
print(temp)
    # 7.pop返回最后一个元素,并且从list中删除
temp = [1,2,3]
print(temp.pop())
print(temp)
    # 8.排序
temp = [1,4,3,6,7,8,2,4]
temp.sort()     # 默认是原始数据改变
print(temp)
temp = [1,4,3,6,7,8,2,4]
temp2 = sorted(temp)      # 保证原始数据不变,把排序后的值赋给新的list
print(temp)     
print(temp2)
print(temp.reverse())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值