Python从0到1——列表(list) 操作
其他常用操作见:Python从0到1_python 把0到1等分为1000个元素-优快云博客
目录
一、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())