python--列表与字典

列表与字典是其他对象类型的集合。

一、内置对象---list(列表),可以包含数字、字符串或其他列表。其属性主要有

        1.任意对象的有序集合,列表就是手机其他对象的对方,同时是有位置顺序的。

        2.通过偏移读取

        3.可变长度、异构和任意嵌套

        4.属于可变序列的分类

        5. 对象引用数组

 实际应用中的列表

        1.基本列表操作         

        >>> len([1,2,3])        #列表长度

        3

        >>> [1,2,3]+[3,4,5]    #合并

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

        >>> [1,2,3]*2            #重复

        [1, 2, 3, 1, 2, 3]

        >>> str([1,2])+"34"    #将列表转换为字符串后合并

        '[1, 2]34'

        >>> [1,2]+list("34")    #将字符串转换列表后合并

        [1, 2, '3', '4']

        >>>

        2.列表迭代和解析(随时盖楼)        

        >>> s=[]

        >>> for c in 'spam':

        ...  s.append(c*4)                #在列表末尾添加新值

        ...

        >>> s

        ['ssss', 'pppp', 'aaaa', 'mmmm']

        >>>

        3.索引、分片和矩阵        

        >>> s=['one','two','three']

        >>> s[1]

        'two'

        >>> s[-1]

        'three'

        >>> s[1:] 

        ['two', 'three']

        >>> s=[[1,2,3],[4,5,6],[7,8,9]]

        >>> s[1]

        [4, 5, 6]

        >>> s[1][1]

        5

        4.原处修改列表

        >>> s=['one','two','three']

        >>> s[0]="I"                        #使用索引赋值的方法在原处修改

        >>> s

        ['I', 'two', 'three']

        >>> s[1:]=["love",'you']        #通过分片方法在原处修改,分片的理解最好分两步,1删除,删除等号左边指定的分片。2插入,将等号右边的对象的片段插入旧分片的位置

        >>> s

        ['I', 'love', 'you']

        >>>

        >>> s[1:2]=[]                        #先删除咯

        >>> s

        ['I', 'you']                #注 实际上分片赋值时一次性替换整个片段的,因为被赋值的序列长度不一定要与被赋值的分片的长度相匹配,所以可以用来替换,增长,缩短主列表。

        5.列表方法

        列表对象也支持特定类型方法调用,方法:是属于特性对象的函数(实际上是引用函数的属性),以下方法只使用于列表

        >>> s

        ['I', 'you']

        >>> s.append('love')        #在列表末尾增加一个单项

        >>> s

        ['I', 'you', 'love']

        >>> s.sort()                    #进行排序,默认是升序(字符串)

        >>> s

        ['I', 'love', 'you']

        >>> s.sort(key=str.lower)        #可以使用name=value语法配置选项,key参数给了一个参数的函数,它返回在排序中使用的值

        >>> s

        ['I', 'love', 'you']

        >>> s.sort(key=str.lower,reverse=True)        #而reverse参数允许使用降序而不是升序

        >>> s

        ['you', 'love', 'I']

        >>>

        注:当使用append和sort原处修改列表对象时,结果并没有返回列表而是NONE,如下

        >>> s

        ['one', 'two', 'three']

        >>> s.append("four")            #使用此方法即可

        >>> s                                

        ['one', 'two', 'three', 'four']

        >>> s=s.append("five")        #这样的修改对象操作 有点副作用,没有理由重新赋值,使用上面的操作即可

        >>> s

        >>>            #这里是none

        >>>

        >>> s=['one','two','three']

        >>> s.extend(['four','five'])        #同时在末尾添加多个项

        >>> s

        ['one', 'two', 'three', 'four', 'five']

        >>> s.pop()                        #删除末尾的项并返回已删除的项

        'five'

        >>> s.reverse()                    #原处反转

        >>> s

        ['four', 'three', 'two', 'one']

        >>> list(reversed(s))            #反转返回新列表,未保存在s中

        ['one', 'two', 'three', 'four']

        >>> s.index('three')                #查找three的偏移值

        1

        >>> s.insert(1,'test')                    #在偏移1处插入test项

        >>> s

        ['four', 'test', 'three', 'two', 'one']

        >>> s.remove('test')                    #删除一个项

        >>> s.pop(1)                        #删除指定偏移的项

        'three'

        >>> s

        ['four', 'two', 'one']

        >>>

        >>> del s[0]        #删除索引为0的项

        >>> s

        ['two', 'one']        #删除分片从偏移0到末尾

        >>> del s[0:]

        >>> s

        []                        #空列表

        >>>

二、字典:无序的集合,是通过键对字典进行索引操作,不是偏移位置存取。

        1.创建方法         

        >>> {'name':'Lili','age':18}                #一次性创建,知道有多少键

        {'name': 'Lili', 'age': 18}

        >>> s={}                                            #动态的创建每一个键及值

        >>> s['name']='Lili'

        >>> s['age']=18

        >>> s

        {'name': 'Lili', 'age': 18}

        >>> dict(name='Lili',age=18)                #代码少,键必须是字符串

        {'name': 'Lili', 'age': 18}

        >>> dict([('name','Lili'),('age',18)])                #程序运行时将键和值逐步建立成序列

        {'name': 'Lili', 'age': 18}

        >>>        

        >>> dict.fromkeys(['a','b'],0)                 #通过fromkeys简单的传入所有键列表,以及所有键的初始值

        {'a': 0, 'b': 0}

        >>>

        >>> dict.fromkeys('fuck')

        {'f': None, 'u': None, 'c': None, 'k': None}

        >>>

        >>> list(zip(['a','b','c'],[1,2,3]))                            #zip函数将对象中对应的元素打包成一个个元组,然后将元组转换为列表

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

        >>> s=dict(zip(['a','b','c'],[1,2,3]))                    #将键和值对应起来传给dict

        >>> s

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

        >>> s={k:v for (k,v)in zip(['a','b','c'],[1,2,3])}            #通过字典解析方法创建字典

        >>> s

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

        >>> s={x:x**2 for x in [1,2,3,4]}        

        >>> s

        {1: 1, 2: 4, 3: 9, 4: 16}

        >>> s={x:x*4 for x in 'fuck'}

        >>> s

        {'f': 'ffff', 'u': 'uuuu', 'c': 'cccc', 'k': 'kkkk'}

        >>>

        2.字典的基本操作         

        >>> s={'x':3,'y':4,'z':'5'}        #用花括号括起来,使用key:value并用逗号隔开的元素

        >>> s['x']            #使用key键取值,而不是偏移

        3

        >>> s

        {'x': 3, 'y': 4, 'z': '5'}

        >>>        

        >>> len(s)        #计算字典的长度

        3

        >>> 'x' in s        #判断键是否存在于字典

        True

        >>> list(s.keys())            #用键来创建一个列表

        ['x', 'y', 'z']

        >>>

        >>> s['x']=['a','b','c']        #在原处直接修改

        >>> s

        {'x': ['a', 'b', 'c'], 'y': 4, 'z': '5'}

        >>> del s['z']                        #del()通过使用key删除一个元素

        >>> s

        {'x': ['a', 'b', 'c'], 'y': 4}

        >>>

        >>> dir(s)                    #字典可用的方法

        ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

        >>> list(s.values())            #通过values方法返回字典中的元素

        [['a', 'b', 'c'], 4]

        >>> list(s.items())            #通过items方法返回字典中的对元组(key,value)

        [('x', ['a', 'b', 'c']), ('y', 4)]

        >>>

        >>> s.get('z')            #使用get()可以判断一个key是否存在并返回其元素

        >>>

        >>> s.get('x')            #使用get()可以判断一个key是否存在并返回其元素并返回其值

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

        >>> print(s.get('z'))            #使用get()可以判断一个key是否存在并返回其元素,若不存在返回none

        None

        >>> s1={'z':5,'a':6}

        >>> s.update(s1)                #将字典s1合并到s中

        >>> s

        {'x': ['a', 'b', 'c'], 'y': 4, 'z': 5, 'a': 6}

        >>> s.pop()                                    #与列表的pop有所不同,列表中pop()可删除最后一个元素并返回其值。但字典不可

        Traceback (most recent call last):

          File "<stdin>", line 1, in <module>

        TypeError: pop expected at least 1 arguments, got 0

        >>> s.pop('a')                                    #通过pop(键)删除一个元素

        6

        >>>s

        {'x': 1, 'y': 2, 'z': 3}

        >>> for i in s:                    #通过迭代字典中的每一个键,打印他们的键和值。此命令等同于 for i in s.keys().

        ...  print(i,'\t',s[i])

        ...

        x        1

        y        2

        z        3

        >>>

        >>> s={1:3,2:2,3:1}              #键不一定是字符串。只要是不可变的对象都可以(除列表外)

        >>> s

        {1: 3, 2: 2, 3: 1}

        >>>

        3.字典视图

        >>> s

        {'f': 'ffff', 'u': 'uuuu', 'c': 'cccc', 'k': 'kkkk'}

        >>> s.keys()

        dict_keys(['f', 'u', 'c', 'k'])

        >>> d=s.keys()

        >>> d

        dict_keys(['f', 'u', 'c', 'k'])

        >>> list(d)

        ['f', 'u', 'c', 'k']

        >>> f=s.values()

        >>> f

        dict_values(['ffff', 'uuuu', 'cccc', 'kkkk'])

        >>> list(f)

        ['ffff', 'uuuu', 'cccc', 'kkkk']

        >>> del s['f']

        >>> s

        {'u': 'uuuu', 'c': 'cccc', 'k': 'kkkk'}

        >>> list(d)

        ['u', 'c', 'k']

        >>> list(f)

        ['uuuu', 'cccc', 'kkkk']

        >>>

        5.字典键排序

        >>> s=dict(zip(['y','a','x'],[1,2,3]))

        >>> s

        {'y': 1, 'a': 2, 'x': 3}

        >>> ks=s.keys()

        >>> list(ks)

        ['y', 'a', 'x']

        >>> ks=list(ks)

        >>> ks

        ['y', 'a', 'x'] 

        >>> ks.sort()                                #sort()

        >>> ks

        ['a', 'x', 'y']

        >>> for k in ks:print(k,s[k])

        ...

        a 2

        x 3

        y 1

        >>>

        >>>

        

        >>> s=dict(zip(['a','c','b'],[1,2,3]))

        >>> s

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

        >>> ks=s.keys()

        >>> ks

        dict_keys(['a', 'c', 'b'])

        >>> sorted(ks)                        #sorted()

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

        >>> for k in sorted(ks):print(k,s[k])

        ...

        a 1

        b 3

        c 2

        >>>

        6.测试字典键是否存在。使用in或者get方法

        

        >>> s

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

        >>> 'a' in s

        True

        >>> print(s.get('a'))

        1

        >>>


猜你喜欢

转载自blog.51cto.com/12107790/2125432