你也的确认你输入的数据是否真的跟你的列表元素一样,才能查询成功;
2.4.7 列表截取(也就是分片)
列表的截取,就是你将列表内的部分数据取出来;
>>> nums
[1, 2, 3, 4, 5, 6, 7]
>>> nums[2]
3
>>> nums[2:4]
[3, 4]
>>> nums[2:6]
[3, 4, 5, 6]
>>> nums[-1]
7
>>> nums[-1:-4]
[]
>>> nums[-1:4]
[]
>>> nums[-2]
6
>>> nums[-4:-1]
[4, 5, 6]
上面的内容说明了一些内容,列表的截取,需要的是,你将里面的内容,按照索引将其截取;
就是,你想截取那几个元素区间,你就将其开始索引值到结束索引值,用:号连接到一起,就可以获取到你想要的区间列表元素值。
2.4.8 列表常用函数与方法
list.append(obj) 在列表末尾添加新的对象
>>> tup1
[1, 2, 3]
>>> tup1.append(3)
>>> tup1
[1, 2, 3, 3]
list.count(obj) 统计某个元素在列表中出现的次数
>>> tup1.count(3)
2
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
>>> tup1
[1, 2, 3, 3]
>>> tup2
[1, 2, 3]
>>> tup2.extend(tup1)
>>> tup2
[1, 2, 3, 1, 2, 3, 3]
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置,索引从0开始
list.insert(index, obj) 将对象插入列表
>>> nums.insert(0,9)
>>> nums
[9, 1, 2, 3, 4, 5, 6, 7]
>>> nums.insert(0,8)
>>> nums
[8, 9, 1, 2, 3, 4, 5, 6, 7]
list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
>>> tup2
[3, 3, 3, 2, 2, 1, 1]
>>> tup2.remove(2)
>>> tup2
[3, 3, 3, 2, 1, 1]
list.reverse() 反向列表中元素,倒转
>>> tup2.reverse()
>>> tup2
[3, 3, 3, 2, 2, 1, 1]
list.sort([func]) 对原列表进行排序
>>> tup2
[1, 2, 3, 1, 2, 3, 3]
>>> tup2.sort()
>>> tup2
[1, 1, 2, 2, 3, 3, 3]
上面函数的调用过程:
>>> tup1 = [1,2,3]
>>> tup2 = [1,2,3]
列表的比较:
>>> tup1 == tup2
True
列表的长度:
>>> len(tup1)
3
列表与元组的互相替换,list 列表,tuple 元组
>>> tuple(tup2)
(3, 3, 3, 2, 1, 1)
>>> list(tup2)
[3, 3, 3, 2, 1, 1]
2.5元组(tuple)
Python的元组与列表类似,不同之处在于元组的元素不能修改;元组使用小括号(),列表使用方括号[];元组创建很简单,只需要在括号中添加元素,并使用逗号(,)隔开即可,例如:
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
创建空元组,例如:tup = ();
元组中只有一个元素时,需要在元素后面添加逗号,例如:tup1 = (50,);
元组与字符串类似,下标索引从0开始,可以进行截取,组合等。
2.5.1 访问元组
如同列表一样,元祖也是由各个元素组成,需要查看那个元素,我们也是使用元组的索引来查看;
查看单个元素
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup2[2]
3
查看元组区间元素
>>> tup2[0:4]
(1, 2, 3, 4)
2.5.2 修改元组
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,例如:
>>> tup1 = (12,32,43)
>>> tup2 = ('abc','efg')
>>> tup1[0] = 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tup3 = tup1 + tup2
>>> tup3
(12, 32, 43, 'abc', 'efg')
2.5.3 删除元组
元组中的元素值是不允许删除的,可以使用del语句来删除整个元组,例如:
>>> del tup3[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> del tup3
>>> tup3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'tup3' is not defined
2.5.4 元组运算符
元组运算符跟列表的一样,也是有 + 与 * ,还有一个关键字in;判断元素是否存在元组中;
>>> tup1 = (1,2,3)
>>> tup2 = (3,4,5)
>>&