zoukankan      html  css  js  c++  java
  • python 基础之第八天--字典相关

    zx

    #####################创建字典######################################

    In [11]: dict([('name','bob'),('age',23),['qq',123456]])
    Out[11]: {'age': 23, 'name': 'bob', 'qq': 123456}
    
    In [12]: dict((('name','bob'),('age',23),['qq',123456]))        ##dict函数
    Out[12]: {'age': 23, 'name': 'bob', 'qq': 123456}
    
    In [13]: aDict = {'name':'bob','age':23,'qq':123456}       ##{}方式
    
    In [14]: aDict
    Out[14]: {'age': 23, 'name': 'bob', 'qq': 123456}

      In [20]: {}.fromkeys(['bob','herry','jerry'],7)      ##不同的key,相同的值,‘7’为值value
      Out[20]: {'bob': 7, 'herry': 7, 'jerry': 7}

    ############关于循环字典取值###############

    In [22]: for key in aDict:        ##默认只取key
       ....:     print key
       ....:     
    qq
    age
    name
    
    In [23]: for key in aDict:       ##key与value一起取
        print '%s-->%s' % (key,aDict[key])
       ....:     
    qq-->123456
    age-->23
    name-->bob
    #########特殊格式输出################
    In [36]: aDict Out[36]: {'age': 23, 'name': 'bob', 'qq': 123456} In [37]: '%(name)s --> %(age)s' % aDict Out[37]: 'bob --> 23'

    ##############删除(不常用),弹出与清空#############

    #######aDict.pop##########
    In [39]: aDict
    Out[39]: {'age': 23, 'name': 'bob', 'qq': 123456}
    
    In [41]: aDict.pop('age')  ###因为字典是无序的,所以需要指名pop哪个key
    Out[41]: 23
    
    In [42]: aDict
    Out[42]: {'name': 'bob', 'qq': 123456}

      In [43]: aDict.popitem()       ###popitem()是随机弹的,几乎用不到,括号内不接受参数
      Out[43]: ('qq', 123456)

      In [46]: uu = aDict.copy()    #复制字典

      In [47]: uu
      Out[47]: {'name': 'bob'}

      In [48]: uu.clear()          ###清空字典

      In [49]: uu
      Out[49]: {}

    ##########字典的in 与not in #############

    In [63]: aDict
    Out[63]: {'age': 23, 'name': 'herry'}
    
    In [64]: 'age' in aDict          ###通过key查看是否在字典中,而不是value
    Out[64]: True

    #############字典长度##############

    In [63]: aDict
    Out[63]: {'age': 23, 'name': 'herry'}
    
    In [66]: len(aDict)
    Out[66]: 2

    ###########判断是否可以作为字典的key##########

    In [67]: hash('naem')
    Out[67]: -4166578487153698939
    
    In [68]: hash(20)    
    Out[68]: 20
    
    In [69]: hash((10,30))
    Out[69]: 3713074054223687331
    
    In [70]: hash([10,30])
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-70-2766bfecf01d> in <module>()
    ----> 1 hash([10,30])
    
    TypeError: unhashable type: 'list'

    总结:通过hash函数,如果不报错,就是可以作为字典的key,我们会发现key都是不可变对象

    #############字典的拷贝################

    In [71]: aDict
    Out[71]: {'age': 23, 'name': 'herry'}
    
    In [72]: bDict = aDict.copy()
    
    In [73]: bDict
    Out[73]: {'age': 23, 'name': 'herry'}
    
    In [74]: aDict
    Out[74]: {'age': 23, 'name': 'herry'}
    
    In [75]: id(aDict)
    Out[75]: 45174528
    
    In [76]: id(bDict)
    Out[76]: 45199760

    ###########字典的get 用法(常用)############

    In [71]: aDict
    Out[71]: {'age': 23, 'name': 'herry'}
    
    In [77]: aDict.get('age')    ###get key为‘age’ 的值23
    Out[77]: 23
    
    In [78]: aDict.get('qq')      ###get 不存在的key,返回值None
    
    In [79]: print aDict.get('qq')
    None
    
    In [80]: aDict.get('qq','not found')      ########自定义,如果get 的key存在,则返回对应的值,不存在则返回我们定义的值,这边是‘not found’
    Out[80]: 'not found'
    
    In [81]: aDict.get('age','not found')  
    Out[81]: 23
    
    In [82]: aDict.get('name','not found')   
    Out[82]: 'herry'

    备注:

      In [83]: help(aDict.get)
      Help on built-in function get:

    get(...)

          D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

     
    In [90]: aDict.setdefault('age',33)      ####setdefault key,存在,则返回相对应的值,不存在则增加key-value
    Out[90]: 20
    
    In [91]: aDict
    Out[91]: {'age': 20, 'name': 'herry'}
    
    In [92]: aDict.setdefault('qq',333333)
    Out[92]: 333333
    
    In [93]: aDict
    Out[93]: {'age': 20, 'name': 'herry', 'qq': 333333}
    
    In [94]: help(aDict.setdefault)
    Help on built-in function setdefault:
    
    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

    ##########################################################

    In [100]: aDict
    Out[100]: {'age': 20, 'name': 'herry', 'qq': 333333}
    
    In [96]: aDict.keys()
    Out[96]: ['qq', 'age', 'name']
    
    In [97]: aDict.values()     
    Out[97]: [333333, 20, 'herry']
    
    In [98]: aDict.items()
    Out[98]: [('qq', 333333), ('age', 20), ('name', 'herry')]

    实战案例:

    ################################################################

    [root@master script]# cat info.py 
    #!/usr/bin/python
    # coding:utf-8
    
    
    user_dic = {'fush':123}
    
    
    def register():
        username = raw_input('请输入你的注册用户名: ')
        password = raw_input('请输入你的注册密码:')
        user_dic.setdefault(username,password)
        print user_dic    
    def login():
        username = raw_input('请输入你的用户名: ')
        while True:
            password = raw_input('请输入你的密码:')
            pwd = user_dic.get(username)
            if str(pwd) == password:
                print '登录系统成功!'
                break
            else:
                print '你输入的密码不正确,请重新输入'
    
    def show_menu():
        CMDs = {'1':register,'2':login}
        username = raw_input('请输入你的用户名: ')
        str_value = user_dic.get(username,'not found')
        if str_value == 'not found':
            print '%s用户名不存在,请输入数字1注册' % username
        else:
            print '%s用户名已存在,可直接输入数字2登录系统' % username
        while True:
            prompt = """(1)注册用户
    (2)登录系统
    (3)退出
    请输入的你的选择(1/2/3):"""
            choice = raw_input(prompt)
            if choice == '3':
                break
            CMDs[choice]()
    if __name__ == '__main__':
        show_menu()

     ###############生成器表达式(与列表解析类似)###############

    In [19]: [i ** 2 for i in range(1,11)]
    Out[19]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    In [20]: [i ** 2 for i in range(1,11) if i%2]
    Out[20]: [1, 9, 25, 49, 81]
    
    In [21]: [i ** 2 for i in range(1,11) if i % 2]
    Out[21]: [1, 9, 25, 49, 81]
    
    In [22]: [i ** 2 for i in range(1,11) if not i % 2]
    Out[22]: [4, 16, 36, 64, 100]
    
    In [23]: (i ** 2 for i in range(1,11) if not i % 2) 
    Out[23]: <generator object <genexpr> at 0x16459b0>
    
    In [24]: a = (i ** 2 for i in range(1,11) if not i % 2)

    案例:打印出一副扑克牌

    puke = ['%s_%s' % (color,i) for color in ('Red','Cube','Black','Flower') for i in (range(2,11) + ['A','J','K','Q'])]
    
    结果:
    ['Red_2',
     'Red_3',
     'Red_4',
     'Red_5',
     'Red_6',
     'Red_7',
     'Red_8',
     'Red_9',
     'Red_10',
     'Red_A',
     'Red_J',
     'Red_K',
     'Red_Q',
     'Cube_2',
     'Cube_3',
     'Cube_4',
     'Cube_5',
     'Cube_6',
     'Cube_7',
     'Cube_8',
     'Cube_9',
     'Cube_10',
     'Cube_A',
     'Cube_J',
     'Cube_K',
     'Cube_Q',
     'Black_2',
     'Black_3',
     'Black_4',
     'Black_5',
     'Black_6',
     'Black_7',
     'Black_8',
     'Black_9',
     'Black_10',
     'Black_A',
     'Black_J',
     'Black_K',
     'Black_Q',
     'Flower_2',
     'Flower_3',
     'Flower_4',
     'Flower_5',
     'Flower_6',
     'Flower_7',
     'Flower_8',
     'Flower_9',
     'Flower_10',
     'Flower_A',
     'Flower_J',
     'Flower_K',
     'Flower_Q']


    In [52]: import random
    In [50]: random.shuffle(puke) #########将扑克牌随机打乱(洗牌)
    三个人打牌:

    In [52]: random.shuffle(puke)

    In [53]: a = puke[::3]

    In [54]: a
    Out[54]:
    ['Red_3',
    'Cube_9',
    'Black_Q',
    'Black_5',
    'Cube_J',
    'Flower_6',
    'Flower_K',
    'Red_Q',
    'Red_5',
    'Cube_2',
    'Cube_4',
    'Flower_8',
    'Flower_9',
    'Red_A',
    'Red_6',
    'Cube_6',
    'Flower_5',
    'Black_7']

    In [55]: b = puke[1::3]

    In [56]: b
    Out[56]:
    ['Cube_3',
    'Cube_A',
    'Cube_5',
    'Black_A',
    'Black_9',
    'Flower_10',
    'Red_10',
    'Cube_K',
    'Flower_2',
    'Black_J',
    'Flower_7',
    'Cube_7',
    'Black_2',
    'Black_8',
    'Cube_8',
    'Black_3',
    'Black_K']

    In [57]: c = puke[2::3]

    In [58]: c
    Out[58]:
    ['Black_10',
    'Red_9',
    'Black_6',
    'Cube_Q',
    'Flower_J',
    'Red_2',
    'Red_K',
    'Red_8',
    'Flower_A',
    'Red_4',
    'Red_J',
    'Flower_3',
    'Flower_Q',
    'Red_7',
    'Cube_10',
    'Black_4',
    'Flower_4']

    ###########文件的输入输出#########################

     #################标准文件的输入与输出################

    #############os模块#####################

    In [19]: import os 
    
    In [20]: import shutil
    
    In [21]: os.chdir('/home')     ###相当于shell 的cd 命令
    
    In [25]: os.mkdir('demo')     ###相当于shell 的mkdir 命令
    
    In [23]: os.getcwd()     ###相当于shell 的pwd 命令
    Out[23]: '/home'
    
    In [29]: os.listdir('.')     ###相当于shell 的ls 命令
    Out[29]: ['herry', 'honey', 'tiantian', 'fush', 'jerry', 'master']

    In [30]: os.mknod('fush.txt') ###创建一个新文件,相当于shell 的touch

      In [41]: os.chmod('/home/11111.txt',0777)     ##修改文件权限,前面需要加0,加0是八进制数,十六进制是0x,二进制是0b

      In [42]: os.symlink('/etc/passwd','mima')    ##创建软链接,将‘/etc/passwd’ 链接到‘mima’

      [root@master home]# ll

      lrwxrwxrwx  1 root  root    11 Aug 14 15:40 mima -> /etc/passwd

      In [50]: os.rmdir('/home/tiantian/')   ##不能删除非空目录,使用shutil.rmtree('/home/tiantian/')

      In [52]: shutil.copy('/etc/hosts','/home/')   ###复制文件

    ##########os.path.操作###############

    In [55]: os.path.dirname('/home/master/script/ip.py')    ##查看上一层目录
    Out[55]: '/home/master/script'
    
    In [63]: os.path.split('/home/master/script/ip.py')    ##切割
    Out[63]: ('/home/master/script', 'ip.py')
    
    In [64]: os.path.basename('/home/master/script/ip.py')        ##取得文件名
    Out[64]: 'ip.py'
    
    In [65]: os.path.join('/home/master/script/','ip.py')      ##拼接目录与文件
    Out[65]: '/home/master/script/ip.py'
    
    In [66]: os.path.splitext('/home/master/script/ip.py')      ###获取点后面扩展名
    Out[66]: ('/home/master/script/ip', '.py')
    
    In [72]: os.path.abspath('info.py')               ##得到文件的绝对路劲
    Out[72]: '/home/master/script/info.py'

    #############cPickle模块###################

    语句例子:

    In [83]: import cPickle as p        #写入
    
    In [84]: f = open('demo.txt','w')
    
    In [85]: p.dump({'name':'bob','age':22},f)
    
    In [86]: f.close()
    
    In [87]: f = open('demo.txt')    #打开读取
    
    In [88]: aDict = p.load(f)
    
    In [89]: aDict
    Out[89]: {'age': 22, 'name': 'bob'}

    #################匿名函数##################

    lambda:

    In [96]: a = lambda x,y :x+y    ###格式: lambda 参数:表达式
    
    In [97]: a(10,20)
    Out[97]: 30
  • 相关阅读:
    坑爹的 Segmentation fault
    静态全局变量得初始化
    新冠肺炎的感受
    \r和\n的区别
    程序里面带有浮点数,默认会自动转换为double类型存储
    Relativity : Fictitious forces
    Biology 04: The Senses
    156 TCP协议的三次握手和四次挥手
    155 大白话OSI七层协议
    154 互联网和互联网的组成
  • 原文地址:https://www.cnblogs.com/shanhua-fu/p/7346889.html
Copyright © 2011-2022 走看看