Python学习-第十二课:列表:一个“打了激素”的数组3
1. 列表的常用操作符
(1)比较:默认从列表的第一个元素开始比较
list1=[0,1,2,3,4]
list2=[0,1,2,4,2]
list1 > list2 运行结果为 Ture;list1 < list2 运行结果为 False
(2)逻辑运算符:and ; or
list1=[0,1,2,3,4]
list2=[0,1,2,4,2]
print((list1 > list2) and (list2 > list1))
print((list1 > list2) or (list2 > list1))
运行结果为:
False
Ture
(3)连接符:+
list1=[0,1,2]
list2=[3,4,5]
print(list1 + list2)
运行结果为:
[0, 1, 2, 3, 4, 5]
(4)重复:*
[1]*4 = [1,1,1,1]
[1*4] = [4]
(5)成员关系:in
1 in [1,2,3] 结果:Ture
1 in [ [ 1 , ‘lmc’ , 2] , 59 ,12] , 结果:False
1 in list1[0],(其中list1 = [ [ 1 , ‘lmc’ , 2] , 59 ,12]) ,结果:Ture
2. 列表的常用操作符
(1)list.append( ): 在列表末尾添加新的对象
用法:列表名.append(添加的对象)
例子1(添加对象为单个元素):
list1=[0,1,2]
list1.append(1)
print(list1)
运行结果:[0, 1, 2, 1]
例子2(添加对象为列表):
list1=[0,1,2]
list1.append([1,2])
print(list1)
运行结果:
[0, 1, 2, [1, 2]]
(2)list.insert( a , b ): 在指定位置添加新的对象
用法:列表名.insert(a , b) ,其中a为插入的对象的位置,b为插入的对象
例子1:
list1=[0,1,2]
list1.insert(0,[1,2])
print(list1)
运行结果:
[ [1, 2], 0, 1, 2]
(3)list.extend( a,b): 在当前列表指定位置增加另一列表内容
PS:注意与list.extend( [ list2 ] )区分
用法:列表名.extend(a) ,其中b为添加列表
例子1:
list1=[0,1,2]
list2=['lmc' , 1 , 2]
list1.extend(list2)
print(list1)
运行结果:
[0, 1, 2, 'lmc', 1, 2]