Python 列表和字典用法解释

  

1、列表可包含任意对象:数字,字符串,其他列表,集合,字典,元组

                例如:

                L = [1,2,3,[12,3]]

                print(L)

                L = [1,2,4,{1,2}]

                print(L)

                L = [1,23,{'a':1,'b':2}]

                print(L)

                L = [1,2,(1,23)]

                print(L)

2、创建列表的方法:

                L = [11,2,3,4]

                或

                L = list('spam')   或者 L = list(range-4,4)

3、列表常用操作

                L = L1 +L2   #返回L1合并L2后的列表

                L1 = [1,2,3,[12,3]]

                print(L1)

                L1.append(4)  #向其末尾增加一个新的元素

                print(L1)   #输出:[1,2,3,[12,3],4]

                L1.extend([1,2,3])  #向其中添加好几个元素

                print(L1)  #输出:[1, 2, 3, [12, 3], 4, 1, 2, 3]

                L1.insert(1,'abc')               #第一个参数是索引位置,第二参数是插入到这个位置值

                print(L1)          #输出:[1, 'abc', 2, 3, [12, 3], 4, 1, 2, 3]

                print(L1.index(1))  #查找元素在列表中第一次出现的位置

                L = [ 1,3,6,2,7]

                L.sort()  #排序

                print(L)     #输出:[1, 2, 3, 6, 7]

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

                L.sort()

                print(L)    #输出:a,b,c,d,e

                #L = [1,5,2,[1,4]]

                #L.sort()          好像只能对数字,或者字母进行排序,而且不能嵌套

                L  = ['ds','a','dsd','ew']

                L.sort()     #输出:['a', 'ds', 'dsd', 'ew']

                print(L)

                L = [1,2,3,[5,2,6]]

                L.reverse()  #将列表倒置,列表中可以包含嵌套

                print(L)

                del L[3]   #删除索引所指的位置上的元素

                print(L)  #输出:[[5, 2, 6], 3, 2]

                del L[1:3]  #删除指定分片范围内的元素

                print(L)  #输出:[[5, 2, 6]]

                L = [1,2,3,4]

                print(L.pop())  #谈出尾部一个元素4 也可以加一个参数,这个参数是索引值

                print(L)      #输出:1,2,3

                L.remove(1)  #删除指定的元素例如这里删除了元素1

                print(L)  #输出:2,3

                L[2:] =[5,6,7]   #在指定分片中插入列表

                print(L)                 #输出:2,3,5,6,7

                L[:0] =[5,6,7]   #在指定分片中插入列表

                print(L)    #输出:[5, 6, 7, 2, 3, 5, 6, 7]

                #也可以利用分片删除某一个范围内的元素

                L[:3]=[]  #删除0-2索引上的元素

                print(L)  #输出:[2, 3, 5, 6, 7]

                #通过索引修改某一个元素的值

                L[0]=-11111111111111111

                print(L)   #输出:[-11111111111111111, 3, 5, 6, 7]

4、分片操作赋值是一次性替换整个片断,而不是在原有基础上先删除,然后再修改

5、L.append(x)方法和L+[x]功能等价,但前者是在原处L处修改ia,而后者会新建一个新的列表,sort原地对列表进行排序

                例如:

                L =['abc','ABC','aBc']

                L.sort()

                print(L)  #输出:ABD,aBc,abc

                L =['abc','ABC','aBc']

                L.sort(key=str.lower,reverse=True)

                print(L)

                排序在最近的python中作为内置函数

                例如:

                L =['abc','ABC','aBc']

                sorted(L,key=str.lower,reverse=True)

                也有内置的reversed函数,但是该函数返回的是一个迭代器

                例如:

                L = [1,2,3,4,5]

                print(reversed(L))   #输出迭代器,所以必须用list函数,而且不是在原处排序

                print(list(reversed(L)))

5、字典

                字典的几种创建方法:

                D =         {}   #创建一个空列表  然后通过 : D['name']='jack',D['age']=25  创建了一个字典 D = {'name':'jack','age':25}

                D = {'name':'tome','age':23}  #直接指定

                D = dict.fromkeys(['a','b','c'])   #输出:  {'a':None,'b':None,'c':None},

                #这个函数有第二个参数,第二个参数是作为值,默认值是None,

                #例如:

                D = dict.fromkeys(['a','b','c'],'not clear')

                print(list(D.items()))  #输出:[('a', 'not clear'), ('c', 'not clear'), ('b', 'not clear')]

                D = dict(zip(keyslist,valueslist)) 

                D = dict (name='tom',age=23)

                print(D)    #输出:{'age': 23, 'name': 'tom'}

                D = dict(zip(['a','b','c'],[1,2,3]))  #输出:{'a': 1, 'c': 3, 'b': 2} 

                #当keyslist和valueslist数目不一致时,以最短的为准,例如:

                D = dict(zip(['a','b','c','d','e'],[1,2,3,5]))  

                print(D)  #输出:{'a': 1, 'c': 3, 'b': 2, 'd': 5}

6、字典的集中常用方法

                D = {'name':'tome','age':23}

                len(D)   #输出:2   这个函数返回的是字典中元素的个数,也是字典中key的数目

                print('name' in D)  #输出:True   这个函数判断给定的键是否存在于字典中

                print(D.keys())  #在python2.6中返回一个真正的列表,但是在python3.0中返回的是一个迭代器,必须用list强制转化为list

                print(list(D.keys()))  #输出:[name,age]

                print(D.values())  #在python2.6中返回一个真正的列表,但是在python3.0中返回的是一个迭代器,必须用list强制转化为list

                print(list(D.values()))  #输出:[tom,23]

                print(D.items())  #在python2.6中返回一个真正的列表,但是在python3.0中返回的是一个迭代器,必须用list强制转化为list

                print(list(D.items()))  #输出:[('age', 23), ('name', 'tom')]

                print(D.get("address","not clear"))  #get方法通过address获得,当这个键不存在时,返回第二个参数,第二个参数默认值是None

                D2 = {'address':'Liaoning','code':'116023','age':'not clear'}

                D.update(D2)  #合并两个字典,当两个键相同时,则覆盖原来这个键对应的值

                print(list(D.items()))  #输出:[('age', 'not clear'), ('code', '116023'), ('name', 'tome'), ('address', 'Liaoning')]

                D.pop(建)  #从字典中删除指定键这个元素,不能使索引

                例如:

                D.pop("age")

                print(list(D.items()))  #输出:[('code', '116023'), ('name', 'tome'), ('address', 'Liaoning')]

7、遍历字典

                for key in D.keys():

                                print(key,'->',D[key])

                或者

                for item in D:

                                print(item,'->',D[item])

                输出都是:

                age -> not clear

                code -> 116023

                name -> tome

                address -> Liaoning

8、数字,字符串,元组,对象等不变对象都可以作为字典的键,列表,集合,字典等可变对象都不能作为字典的键

                例如:

                D = {1:'tome','age':23}

                print(list(D.items()))

                D = {1:'tome',(1,2):23}

                print(list(D.items()))

                class A:

                                pass

                a = A()

                D = {a:1}

                print(list(D.items()))

                输出:

                [(1, 'tome'), ('age', 23)]

                [((1, 2), 23), (1, 'tome')]

                [(<__main__.A object at 0xb7334b4c>, 1)]

9、当键不存在字典中时,系统会抱错,以下三种方法处理这种情况

                D = {'a':1,'b':2,'c':3}

                if 'd' in D:

                                print(D[d])

                else :

                                print('Not exist')

               

                #或者

                try :

                                print(D['d'])

                except KeyError:

                                print('Not exist')

 

                #或者

                print(D.get('d','Not exist'))

 

10、字典在python3.0中的变化

                1、有字典解析式

                2、keys(),values(),items()返回的是视图,而不是列表

                3、不能直接比较大小

                4、没有has_key判断某一个键是否存在

11、zip函数的使用

                list(zip(['a','b','c'],[1,2,3]))

                #输出:[('a', 1), ('b', 2), ('c', 3)]

12、字典解析式

                D = {s:s*2 for s in [1,2,3,4]}  #输出:[(1, 2), (2, 4), (3, 6), (4, 8)]

13、在python3.0中,keys(),values(),items(),这些视图创建后,这些视图可以动态的反映对原字典的修改,例如:               

                D = {'a':1,'b':2,'c':3}

                k = D.keys()

                v = D.values()

                i = D.items()

                print(list(k))  #输出:'a','b','c'

                print(list(v))        #输出:1,2,3

                print(list(i))  #输出:{'a':1,'b':2,'c':3}

                D['d']=4  #增加一个元素

                print(list(k))  #输出:'a','b','c','d'

                print(list(v))        #输出:1,2,3,4

                print(list(i))  #输出:{'a':1,'b':2,'c':3,'d':4}

14、字典视图和集合

                视图可以与其他试图,集合,字典混合操作

                例如:

                键试图:

                D = {'a':1,'b':2,'c':3}

                k = D.keys()

                #键视图与字典

                print(k|{'x':90})  #输出:{'a', 'x', 'c', 'b'}

                #键试图 与集合

                print(k|{'t','k'})  #输出:{'a', 'c', 'b', 'k', 't'}

                #键视图与建视图

                d = {'i':23,'z':543}

                print(k|d.keys())  #输出:{'a', 'i', 'c', 'b', 'z'}

               

                items试图:

                D = {'a':1,'b':2,'c':3}

                k = D.items()

                #视图与字典

                print(k|{'x':90})  #输出:{('a', 1), 'x', ('b', 2), ('c', 3)}   #把字典中的键和原字典中的键和值当作元组加入到集合中

                #试与集合

                print(k|{'t','k'})  #输出:{('a', 1), ('b', 2), ('c', 3), 'k', 't'}  #把集合中的值和原字典中的键和值当作元组加入到集合中

                #试图与视图

                d = {'i':23,'z':543}

                print(k|d.items())  #输出:{('a', 1), ('z', 543), ('b', 2), ('c', 3), ('i', 23)} #把新字典中的键和值当作元组和原字典中的键和值当作元组加入到集合中

15、字典排序:            

                方法一:

                D = {'a':1,'d':2,'c':3}

                k = D.keys()

                temp = list(k) #因为返回值是试图所以不能对其直接排序,必须转化为列表

                temp.sort()

                for k in temp:

                                print(k,'->',D[k])

                方法二:

                D = {'a':1,'d':2,'c':3}

                k = D.keys()

                for k in sorted(k):

                                print(k,'->',D[k])

  

原文地址:https://www.cnblogs.com/hbcb533/p/3671403.html