列 表
列表在python里是有序集合对象类型。
列表里的对象可以是任何对象:数字,字符串,列表或者字典,元组。与字符串不同,列表是可变对象,支持原处修改的操作
python的列表是:
- 任意对象的有序集合
- 通过偏移读取
- 可变长度、异构以及任意嵌套
- 属于可变序列的分组
- 对象引用数组
列表的操作
列表的操作和字符串大部分都相同:
合并/重复:
- list1+list2:结果是两个列表按顺序结合
- list*3:结果是列表list重复三次
- for i in list1: print(i):按顺序打印列表里的内容
- 3 in list:判断列表里有没有一个对象是对象3
- list1.index(1):查找列表里第一个为1的对象的位置
- list1.count(1):查找列表里对象为1的个数
- list1[x:y]:取第x到y的对象,重新建立一个列表
- len(list1):list1里的对象个数
基本列表操作
- 创建一个列表:
>>> list=[] >>> list=[1,2,'3',[]] >>> list [1, 2, '3', []]
- 列表取值:
>>> list[1] 2 >>> list[0:3] [1, 2, '3']
- 重复列表内容:
>>> list*3 [1, 2, '3', [], 1, 2, '3', [], 1, 2, '3', []]
- 使用in方法来判断对象是否在列表中:
>>> 3 in listFalse >>> [] in list True
- 循环打印:
>>> for i in list: ... print (i,end=' ') ...1 2 3 []
- 迭代方式创建列表:
>>> list=[i*4 for i in 'ASDF' ] >>> list ['AAAA', 'SSSS', 'DDDD', 'FFFF']
- 矩阵:
list=[ [1,2,3,],[4,5,6],[7,8,9] ] >>> list [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> list[0][1] 2 >>> list[1][2] 6
- 列表原处修改:
>>> food=['spam','eggs','milk'] >>> food[1]'eggs' >>> food[1]='Eggs' >>> food[:] ['spam', 'Eggs', 'milk']
列表的方法
- 列表的添加:
>>>food.append('cake') >>> food ['spam', 'Eggs', 'milk', 'cake']
- 列表的排序:
>>> food.sort() >>> food ['Eggs', 'cake', 'milk', 'spam']
- 合并列表:
>>> list1=[1,2,3] >>> list2=[4,5,6] >>> list1.extend(list2) >>> list1 [1, 2, 3, 4, 5, 6]
- 列表的取值:
>>> list1.pop() 6 >>> list1 [1, 2, 3, 4, 5]
- 列表倒序显示:
>>> list1 [1, 2, 3, 4, 5] >>> list1.reverse() >>> list1 [5, 4, 3, 2, 1]
- 列表的索引:
>>> list=[1,2,3,4,5] >>> list.index(3) 2
- 列表的插入:
>>> list.insert(2,10) >>> list [1, 2, 10, 3, 4, 5]
- 删除列表的某一个对象:
>>> list [1, 2, 10, 3, 4, 5] >>> del list[2] >>> list [1, 2, 3, 4, 5]
- 列表的排序:
列表的排序默认是先以字母大小写进行排序的,可以在列表中加一个选项key=lower.str使其都转换成小写,使用reverse=True进行倒序排列
>>> list=['abc','aDd','ace'] >>> sorted(list) ['aDd', 'abc', 'ace'] >>> list ['abc', 'aDd', 'ace'] >>> sorted(list,key=str.lower,reverse=True) ['aDd', 'ace', 'abc'] >>> sorted(list,key=str.lower) ['abc', 'ace', 'aDd'] >>>sorted([x.lower() for x in list]) ['abc', 'ace', 'add'] >>> sorted([x.lower() for x in list],reverse=True) ['add', 'ace', 'abc']
列表的实际用法
- 取值:
>>> info=['myname',18,[1997,9,28]] >>> _name,_age,_birth=info >>> _name'myname' >>> _age 18 >>> _birth [1997, 9, 28] >>> _name,_age,(_birth_y,_birth_m,_birth_d)=info >>> _birth_y 1997 >>> _birth_m,_birth_d (9, 28)
当取的值不固定的时候,可以用*代替:
>>> a=['adc',122,2215,'asd@asd'] >>> a_name,*a_phone,a_mail=a >>> a_name 'adc' >>> a_phone [122, 2215]
- 只保留列表里最后N个元素:
使用deque函数可以设置列表中的元素个数,如果超过列表最大限制,那么会将列表里最左边的元素删掉,如果是在左边添加的,那么删除的是最右边的元素
>>> from collections import deque >>> q=deque(maxlen=3) >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q deque([1, 2, 3], maxlen=3) >>> q.append(4) >>> q deque([2, 3, 4], maxlen=3) >>> q.appendleft('5') >>> q deque(['5', 2, 3], maxlen=3)
- 取出列表中的最大值和最小值:
使用heapq模块的nlargest,nsmallest方法来取出列表中的几个最大值和最小值,当然也可以使用max和min函数来求最大和最小,使用sum函数来求列表数字的和
>>> from heapq import nlargest,nsmallest >>> num=[1,4,6,7,8,8,34,64,23,7,45,34] >>> nlargest(3,num) [64, 45, 34] >>> nlargest(2,num) [64, 45] >>> nsmallest(2,num) [1, 4] >>> nsmallest(4,num) [1, 4, 6, 7] >>> num [1, 4, 6, 7, 8, 8, 34, 64, 23, 7, 45, 34] >>> max(num) 64 >>> min(num) 1 >>> sum(num) 241 >>> a_info=['wanger','wangerxiao',25,'computer'] >>> _name=slice(0,2) >>> _age=slice(2,3) >>> _job=slice(3,4) >>> a_info[_name] ['wanger', 'wangerxiao'] >>> a_info[_age] [25] >>> a_info[_job] ['computer']
- 重复元素计算:
这会用到collections模块的Counter方法
>> a=[1,2,3,4,5,6,2,4,2,5,6] >>> from collections import Counter >>> count_word=Counter(a) >>> count_word Counter({2: 3, 4: 2, 5: 2, 6: 2, 1: 1, 3: 1}) >>> count_word.most_common(3) [(2, 3), (4, 2), (5, 2)] >>> count_word.most_common(2) [(2, 3), (4, 2)]
字典
字典在python里是无序集合对象类型。
字典的值都有独立的唯一的键,用相应的键来取值。
python字典主要特性如下:
- 通过键而不是偏移量来读取
- 任意对象的无序组合
- 可变长,异构,任意嵌套
- 属于可映射类型
- 对象引用表
字典用法注意事项:
- 序列运算无效——串联,分片不能使用
- 对新索引(键)赋值会添加项
- 键不一定是字符串——只要是不可变的对象(列表字典除外)
字典的基本操作:
- 字典的赋值:
>>> dict={'a':97,'b':98} >>> len(dict) 2 >>> print("ascii code of 'a' is {},ascii code of 'b' is {}".format(dict['a'],dict['b'])) ascii code of 'a' is 97,ascii code of 'b' is 98
- 判断特定的键是否存在于字典里:
>>> 'a' in dict True >>> 'b >>>> 'b' is in dict True
- 原处修改:
#更改特定键的值 >>> food={'eggs':3,'ham':1,'spam':4} >>> food['ham']=2 >>> food {'eggs': 3, 'ham': 2, 'spam': 4} #增加新的键和相应的值 >>> food['branch']=['bacon','bake'] >>> food {'eggs': 3, 'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']} #删除一个字典元素 >>> del food['eggs'] >>> food {'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']} #清空字典所有条目 >>> dict.clear() #删除字典 del dict
字典的方法
- 查找字典的键值是否存在,如果不存在可以设置返回的值
>>> food.get('ham') 2 >>> dict.get('b') 2 >>> dict.get('0') >>> dict.get('0','none') 'none'
- 创建字典的方法:
1.最原始的方法:
dict={'name':'wanger','age':25}
2.按键赋值方法:
>>> dict={} >>> dict['name']='wanger' >>> dict['age']=25
- 字典的比较:
字典的比较会比较字典的键,而不是字典的值,可以使用zip方式将字典的值和键反过来,这样就会比较值了,可以使用sorted函数对字典进行排序
>>> dict={'a':1,'b':2,'c':3,'d':4} >>> max(dict) 'd' >>> min(dict) 'a' >>> max(zip(dict.values(),dict.keys())) (4, 'd') >>> min(zip(dict.values(),dict.keys())) (1, 'a') >>> sorted(zip(dict.values(),dict.keys())) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] >>> sorted(zip(dict.values(),dict.keys()),reverse=True) [(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
- 字典列表的排序:
可以使用sorted函数进行排序,使用key参数可以对排序的键进行定义,这里要用到operator模块的itemgetter函数
>>> rows [{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'John', 'lname': 'Clesse', 'uid': 1001}, {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}] >>> from operator import itemgetter >>> rows_fname=sorted(rows,key=itemgetter('fname')) >>> rows_fname [{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}, {'fname': 'Brian', 'lname':'Jones', 'uid': 1003}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'John', 'lname': 'Clesse', 'uid': 1001}] >>> rows_uid=sorted(rows,key=itemgetter('uid')) >>> rows_uid [{'fname': 'John', 'lname': 'Clesse', 'uid': 1001}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]
元组
元组简介
元组与列表非常类似,只是不能在原处更改,元祖在python里的特点:
- 任意对象的有序组合
- 通过偏移取数据
- 属于不可变序列类型
- 固定长度,异构,任意嵌套
- 对象引用的数组
元组的创建
元祖创建在只有单个元素的时候,必须加逗号(,),元组里可以嵌套元组
>>> tuple=() >>> tuple=(1,) >>> type(tuple) <class 'tuple'> #这里加不加括号都一样 >>> tuple=(1,2,'3',(4,5)) >>> tuple (1, 2, '3', (4, 5)) >>> tuple=1,2,'3',(4,5) >>> tuple (1, 2, '3', (4, 5))
将列表转换为元组
>>> list=[1,2,3,4] >>> sd=tuple(list) >>> sd (1, 2, 3, 4)
元组的方法
- 元组的排序:
元组经过sorted排序后,会将其转换为列表
>>> tuple=(1,5,3,6,4,2) >>> sorted(tuple) [1, 2, 3, 4, 5, 6]
- 查找元组元素位置:
>>> tuple (1, 5, 3, 6, 4, 2) >>> tuple.index(3) 2
- 计算元组元素数目:
>>> tuple (1, 5, 3, 6, 4, 2) >>> tuple.count(3) 1
- 元组的切片:
>>> tuple[0] 1 >>> tuple[2:] (3, 6, 4, 2) >>> tuple[2:3] (3,)
- 列表和元组的操作类似,列表操作里只要不是在原处修改的,都可用于元组
>>> (1,2)+(3,4) (1, 2, 3, 4) >>> (1,2)*4 (1, 2, 1, 2, 1, 2, 1, 2) >>> len(tuple)
集合
集合简介
set是一个无序且不重复的元素集合
集合对象十一组无序排列的可哈希的值,集合成员可以做字典中的键。set也支持用in 和not in操作符检查成员,由于集合本身是无序的,不可以为集合创建索引或执行切片操作,也没有键可用来获取集合中元素的值。
集合特点
- 集合中的元素和字典中的键一样不重复
- 集合中的元素为不可变对象
集合的创建
>>> s=set('a') >>> a=set({'k1':1,'k2':2}) >>> b=(['y','e','d','o']) >>> c={'a','b','c'} >>> d={('a','b','c')}
集合基本操作
- 集合的比较
#比较a、b集合中a中存在,b中不存在的集合 >>> a={11,22,33} >>> b={11,23,45} >>> a.difference(b) {33, 22} #找到a中存在,b中不存在的集合,并把a、b集合中都有的值覆盖掉 >>> a={11,22,33} >>> print(a.difference_update(b)) None >>> a {33, 22}
- 集合的删除:
>>> a={11,22,33} >>> a.discard(11) >>> a.discard(44) >>> a {33, 22} #移除不存在的元素会报错 >>> a={11,22,33} >>> a.remove(11) >>> a.remove(44) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 44 >>> a {33, 22} #移除末尾的元素 >>> a={11,22,33} >>> a.pop() 33 >>> a {11, 22}
- 取交集:
#取交集赋给新值 >>> a={1,2,3,4} >>> b={6,5,4,3} >>> print (a.intersection(b)) {3, 4} #取交集并把交集赋给a >>> print (a.intersection_update(b)) None >>> a {3, 4}
- 集合判断:
>>> a={3,4} >>> b={6,5,4,3} #判断a是否与b没有交集,有交集False,无交集True >>> a.isdisjoint(b) False #判断a是否是b的子集 >>> a.issubset(b) True #判断a是否是b的父集 >>> a.issuperset(b) False
- 集合合并:
>>> a={1,2,3,4} >>> b={3, 4, 5, 6} #打印不同的元素 >>> print (a.symmetric_difference(b)) {1, 2, 5, 6} #打印不同的元素,并覆盖到集合a >>> print (a.symmetric_difference_update(b)) None >>> a {1, 2, 5, 6}
- 集合取并集:
>>> a={1, 2, 5, 6} >>> b={3, 4, 5, 6} >>> print (a.union(b)) {1, 2, 3, 4, 5, 6}
- 集合的更新:
>>> a={1, 2, 5, 6} >>> b={3, 4, 5, 6} #把a、b的值合并,并把值赋给集合a >>> a.update(b) >>> a {1, 2, 3, 4, 5, 6} #添加a集合的元素 >>> a.update([7,8]) >>> a {1, 2, 3, 4, 5, 6, 7, 8}
- 集合的转换:
将集合分别转换为列表、元组、字符串
>>> a=set(range(5))>>> li=list(a) >>> tu=tuple(a) >>> st=str(a) >>> print (li) [0, 1, 2, 3, 4] >>> print (tu) (0, 1, 2, 3, 4) >>> print (st) {0, 1, 2, 3, 4}