Python列表可以同时包含数据、字符串、对象、列表等数据类型
List1 = [1, 2, 'abc', 'def']List2 = [5, 6, [1, 2, 'abc']]
(1) append()
append()方法可用于在列表的最后追加一个元素
append(<插入的元素>)List1.append('newItem') #append方法只能有一个参数print(List1)输出结果:[1, 2, 'abc', 'def', 'newItem']
(2) extend()
extend()方法用于在列表的最后扩展另一个列表
extend(<拓展的列表>)List1.extend([3, 4]) #extend方法同样只能有一个参数print(List1)输出结果:[1, 2, 'abc', 'def', 'newItem', 3, 4]
(3) insert()
insert()方法可在列表任意位置插入元素
insert(<插入位置>, <插入的元素>)List1.insert(1, 'insertItem')print(List1)输出结果:[1, 'insertItem', 2, 'abc', 'def', 'newItem', 3, 4]
(1) remove()
remove()方法可以移除列表中的一个已知元素
remove(<删除的元素>)List1 = [1, 'insertItem', 2, 'abc', 'def', 'newItem', 3, 4]List1.remove('newItem') #不需要知道元素的位置print(List1)输出结果:[1, 'insertItem', 2, 'abc', 'def', 3, 4]
(2) del
del语句可以按下标删除元素
del 列表名[<下标>]del List1[2] # del是Python的语句,不是方法print(List1)输出结果:[1, 'insertItem', 'abc', 'def', 3, 4]
(3) pop()
pop()方法可以删除并返回指定位置的元素
pop(<要删除元素的位置>) #如果没有参数则默认删除最后一个元素item = List1.pop()print(List1)print(item)输出结果:[1, 'insertItem', 'abc', 'def', 3] 4
列表名[<分片开始位置>: <分片结束位置>: <步长>] '''若不写开始位置则默认从第一个位置开始若不写结束位置则默认从最后个位置结束若不写步长则默认步长为1'''List1 = [1, 'insertItem', 'abc', 'def', 3]print(List1[1:4]) #分片不改变原列表内容print(List[2:])print(List[:4:2])输出结果:['insertItem', 'abc', 'def'] ['abc', 'def', 3] [1, 'abc']
分片还支持负数索引以及负步数
步长可以是负数,改变方向(从尾部开始向左走):print(List1[::-2])输出结果:[3, 'abc', 1]
列表复制应使用分片
List1 = [1, 'insertItem', 'abc', 'def', 3]copy1 = List1[:] #将List1的内容复制到copy1中copy2 = List1 #若直接赋值,copy2和List1指向同一内容,若对List1进行操作,copy2也被改变
(1) 比较操作符
list1 = [123, 456]list2 = [234, 123]list1 > list2 #把列表的第0个位置进行比较输出结果:false
(2) 列表拼接
list3 = list1 + list2 #用加号进行拼接print(list3)输出结果:[123, 456, 234, 123]
不可以使用加号添加单个元素
list3 + ‘newItem’
(3) 列表重复
print(list1 *= 3)输出结果:[123, 456, 123, 456, 123, 456]
(4) 成员关系操作符
123 in list1输出结果:true234 not in list2输出结果:falselist4 = [123, ['abc', 'def'], 456]'abc' in list4输出结果:false #成员关系操作符默认判断最外层列表'abc' in list4[1]输出结果:true
(1) count()
count()方法的作用是判断某一元素在列表中的出现次数
count(<要判断的元素>)list5 = [1, 1, 1, 2, 3]list5.count(1)输出结果:3
(2) index()
index()方法用于查询某一元素在列表中的位置
index(<要查询的元素>, <查询范围起始位置>, <查询范围的结束位置>) #后两个参数不写则默认范围为整个列表list5.index(2)输出结果:3
(3) reverse()
reverse()方法的作用是将列表前后翻转
list5.reverse()print(list5)输出结果:[3, 2, 1, 1, 1]
(4) sort()
sort()方法则作用是用指定方法对列表进行排序
sort(<func>, <key>, <reverse=True/False>) #reverse默认为truelist6 = [8, 3 ,5 ,2 ,5, 0, 1]print(list6.sort()) #默认为从小到大排序输出结果:[0, 1, 2, 3, 5, 5, 8]print(list6.sort(reverse = True))输出结果:[8, 5, 5, 3, 2, 1, 0]
https://www.cnblogs.com/augustcode/p/Python_2.html
联系客服