Python中列表与元组的使用

来源:互联网 发布:詹姆斯11年总决赛数据 编辑:程序博客网 时间:2024/06/05 04:03

Python中列表与元组的使用

列表list是一个可改变的序列,元组是不可改变的。

定义一个列表:list = [a,b,c,d,] #定义一个列表使用‘[]’,或者list('abcd')是不是很像构造函数大笑,列表并没有对列表中元素的类型做限制

>> list = ['a','b',1,2]
>>> list
['a', 'b', 1, 2]
>>> list.append(0.3)
>>> list
['a', 'b', 1, 2, 0.3]
>>> list.append('True')
>>> list
['a', 'b', 1, 2, 0.3, 'True']

定义一个元组:tuple = (a,b,c,d,)#定义一个元组使用‘()’,或者tuple('abcd'),如若想要使用的元组不为空,必须在定义时就进行初始化,就像C++中的引用在定义时必须初始化。或者一个const修饰的类型必须在定义的时候初始化之后不允许对其进行修改。

列表与元组跟C++中的容器很相似,以及之后会介绍的Python中的字典与C++容器中的map很相似都是键值对的存储方式,且键key不可重复。

Python中列表的使用:

1 append(self, x)方法,在列表尾部添加x

list = ['a','b','c','d']list.append('1')print(list)
输出:

['a', 'b', 'c', 'd', '1']

2 extend(self, t)方法,使用t中的内容扩充列表

list = ['a','b','c','d']list.extend('12345')print(list)
输出:

['a', 'b', 'c', 'd', '1', '2', '3', '4', '5']

3 count(self, x)方法,统计x在列表中出现的次数

list = ['a','b','c','d','c']test = list.count('c')print(test)
输出:

2

4 index(self, x, i=None, j=None)方法,返回x在列表中出现的位置,可指定开始与结束位置

list = ['a','b','c','d','c']test = list.index('c',3,5)print(test)
输出:

4

list = ['a','b','c','d','c']test = list.index('c')print(test)
5 insert(self, i, x)方法,将x插入列表中i的位置处

list = ['a','b','c','d',]list.insert(6,'1')print(list)
输出:

['a', 'b', 'c', 'd', '1']

6 pop(self, i=-1)方法,移除并返回列表中的元素默认为最后一个

list = ['a','b','c','d',]test = list.pop()print(list)print(test)
输出:

['a', 'b', 'c']
d

list = ['a','b','c','d',]test = list.pop(1)print(list)print(test)
输出:

['a', 'c', 'd']
b

7 remove(self, x)删除列表中的x

list = ['a','b','c','d',]list.remove('b')print(list)
输出:

['a', 'c', 'd']

8 def sort(self, cmp=None, key=None, reverse=False)方法,排序列表

list1 = [3,4,6,8,1,5,2]list1.sort()print(list1)
输出:

[1, 2, 3, 4, 5, 6, 8]

安装规则排序

使用参数key,按照长度进行排序

list = ['ab','drt','ewer','cuioy','uqwerg',]list.sort(key=len)print(list)
输出:

['ab', 'drt', 'ewer', 'cuioy', 'uqwerg']

使用参数reverse,倒序排序

list = ['uqwerg','drt','ab','ewer','cuioy',]list.sort(key = len,reverse=True)print(list)
输出:

['uqwerg', 'cuioy', 'ewer', 'drt', 'ab']

Python中元组的使用

由于元组是不可修改的,故元组没有列表中那么多方法。

1 count(self, x)方法,返回元素x在元组中出现的次数

tuple = (1,2,3,12,2,23,2,4)count = tuple.count(2)print(count)
输出:

3

index(self, x, i=None, j=None)方法,返回x出现的位置可指定起始与结束位置

tuple = (1,2,3,12,2,23,2,4)count = tuple.index(2)print(count)
输出:

1

tuple = (1,2,3,12,2,23,2,4)count = tuple.index(2,2,5)print(count)
输出:

4

0 0
原创粉丝点击