python入门第六天
Python3 List clear()方法
描述
clear() 函数用于清空列表,类似于 del a[:]。
语法
clear()方法语法:
list.clear()
举例:
1 list3 = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 2 print(list3) 3 4 list3.clear() 5 print(list3)
结果:清除数据后,类别依然存在。但是列表内没有数据
"D:\Program Files (x86)\python36\python.exe" F:/python从入门到放弃/6.5/list复习.py [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] [] Process finished with exit code 0
Python 的元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
举例:
1 students=(('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)) 2 print(students) 3 4 courses=('语文','数学','地理','物理') 5 6 print(courses) 7 8 courses2='英语','化学','地理','物理' 9 10 print(type(courses2)) 11 12 tup1=2,5,'郭靖','黄蓉' 13 14 print(type(tup1))
结果:
=================== RESTART: F:\python从入门到放弃\6.5\list复习.py =================== (('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)) ('语文', '数学', '地理', '物理') <class 'tuple'> <class 'tuple'> >>>
访问元组
元组可以使用下标索引来访问元组中的值,如下实例:
1 >>> tup=(('name','Tom'),('age',78)) 2 >>> tup 3 (('name', 'Tom'), ('age', 78)) 4 >>> type(tup) 5 <class 'tuple'> 6 >>> tup1=('name','age') 7 \ 8 >>> tup1 9 ('name', 'age') 10 >>> type(tup1) 11 <class 'tuple'> 12 >>> tup[0] 13 ('name', 'Tom') 14 >>> tup1[1] 15 'age' 16 >>>
修改元组
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:
1 >>> tup1=('name','age','gender') 2 >>> tup2=('Tom','23','男') 3 >>> tup2[2]='man' 4 Traceback (most recent call last): 5 File "<pyshell#10>", line 1, in <module> 6 tup2[2]='man' 7 TypeError: 'tuple' object does not support item assignment 8 >>> tup1+tup2 9 ('name', 'age', 'gender', 'Tom', '23', '男') 10 >>>
删除元组
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:
>>> tup1=('name','age','gender') >>> tup2=('Tom','23','男') >>> tup3=tup1+tup2 >>> tup3 ('name', 'age', 'gender', 'Tom', '23', '男') >>> del tup3 >>> tup3 Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> tup3 NameError: name 'tup3' is not defined >>>
元组运算
>>> tup1=('name','age','gender') >>> len(tup1) 3 >>> tup1*2 ('name', 'age', 'gender', 'name', 'age', 'gender') >>> 'age' in tup1 True >>> for x in tup1:print(x,end='\t') name age gender >>>
元组索引,截取
因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素。
元组内置函数
>>> tuple1=('道君','圣墟','五行天','大王饶命','汉祚高门','一念永恒','天骄战纪') >>> len(tuple1) 7 >>> max(tuple1) '道君' >>> min(tuple1) '一念永恒' >>> list1=[2,3,9,4,5,6,7,1] >>> tuple2=tuple(list1) >>> type(list) <class 'type'> >>> type(tuple2) <class 'tuple'> >>> min(tuple2) 1 >>> max(tuple2) 9 >>> len(tuple2) 8 >>>

浙公网安备 33010602011771号