
list_new = list()
new_list = []
#⚠️这两种定义方式都是可以的
定义一个非空列表,列表中的元素是任意的,元素可以是任何类型
list_new = [1,'hello',[1,3],False,{'name':'william'},{1,4},(3,5)]
切片获取元素
print(list_new[2:5])
#打印结果:[[1, 3], False, {'name': 'william'}]
切片反转列表
print(list_new[::-1])
#打印结果:[(3, 5), {1, 4}, {'name': 'william'}, False, [1, 3], 'hello', 1]
切片按步长获取元素
print(list_new[1,6:2]) #从一个元素到第六个元素但不包含第六个元素,每两个元素获取一个元素
#打印结果:['hello', False, {1, 4}]
获取列表中指定元素
print(list_new[1])
#打印结果:hello
#⚠️获取的是列表中第2个元素,列表中的索引是从0开始的
index()方法:获取指定元素的索引(index)
ind=list_new.index('hello')
print(ind)
#打印结果: 1
#⚠️列表中的‘hello’元素索引值是1
insert()方法:在列表指定位置插入元素
list_new.insert(2,'world')
print(list_new)
#打印结果:[1, 'hello', 'world', [1, 3], False, {'name': 'william'}, {1, 4}, (3, 5)]
#⚠️insert()方法需要传入两个参数形如:insert(index,value),index是列表中要插入元素的索引位置,value是要插入的元素值
extend()方法:扩展序列
list1=[1,2]
list2=[3,4]
list1.extend(list2)
print(list1)
#打印结果:[1, 2, 3, 4],相当于list1+=list2
append()方法:添加元素
list3=['hello','world',1]
for i in "hey":
list3.append(i)
print(list3)
#打印结果:['hello', 'world', 1, 'h', 'e', 'y']
#append()方法是将添加的元素放到序列最后的位置
pop()方法:删除指定索引的元素或删除最后一个元素
list4=['hello','william','what','gorgeous']
list4.pop(2)
print(list4)
#打印结果:['hello', 'william', 'gorgeous'] 索引为2的第3个元素被删除
list4.pop()
print(list4)
#打印结果:['hello', 'william'] 最后一个元素被删除
clear()方法:清空列表
list5=[1,2,3,4,5,6]
list5.clear()
print(list5)
#打印结果:[] 列表已经被清空了
remove()方法:删除指定元素
list6=[[1,3],3,'he',5,True]
list6.remove('he')
print(list6)
#打印结果:[[1, 3], 3, 5, True]
del 删除指定元素
list7=[1,2,3,4,5,6]
del list7[0] #删除第1个元素
print(list7)
#打印结果:[2, 3, 4, 5, 6] 列表中的第一个元素已经被删除
reverse()方法:翻转列表
list_new.reverse()
print(list_new)
#打印结果:[(3, 5), {1, 4}, {'name': 'william'}, False, [1, 3], 'hello', 1]
#⚠️翻转过后的列表,和原列表的id是相同的。
sort()方法:对列表中的元素进行排序
#为了更好的表示,新建一个只有数字的列表
targetList=[100,6,10,2,5,0,11,-1]
targetList.sort()
print(targetList)
#打印结果:[-1, 0, 2, 5, 6, 10, 11, 100]
sorted()方法:如果不想改变原列表,可以使用sorted()进行排序
target_list=[100,6,10,2,5,0,11,-1]
print(sorted(target_list))
#打印结果:[-1, 0, 2, 5, 6, 10, 11, 100]
print(target_list)
#打印结果:[100, 6, 10, 2, 5, 0, 11, -1]
#⚠️sorted()方法可以对列表进行排序,但是不回改变原列表内元素的顺序
sort()方法扩展:倒叙排序
#为了更好的表示,新建一个只有数字的列表
targetList=[100,6,10,2,5,0,11,-1]
targetList.sort(reverse=True)
print(targetList)
#打印结果:[100, 11, 10, 6, 5, 2, 0, -1]
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)