字典和集合、时间方法、异常处理、文件系统相关模块

一、字典和集合

1.1 字典基础操作

1.1.1 创建字典

1. 通过{ }操作符创建字典
2. 通过dict()工厂方法创建字典
3. 通过fromkeys()创建具有相同值的默认字典

>>>    adict    =    {'name':'bob',    'age':23}    
>>>    bdict    =    dict((['name',    'bob'],    ['age',    23]))    
>>>    print(bdict)    
{'age':    23,    'name':    'bob’}    
>>>    cdict    =    {}.fromkeys(('bob',    'alice'),    23)    
>>>    print(cdict)    
{'bob':    23,    'alice':    23}    

1.1.2 访问字典

1. 字典是映射类型,意味着它没有下标,访问字典中的
值需要使用相应的键

>>>    for    each_key    in    adict:    
...          print    'key=%s,    value=%s'    %    (each_key,    adict[each_key])    
key=age,    value=23    
key=name,    value=bob    
    
>>>    print('%(name)s'    %    adict)    
bob    

1.1.3 更新字典

1.通过键更新字典
–  如果字典中有该键,则更新相关值
–  如果字典中没有该键,则向字典中添加新值

>>>    print    adict    
{'age':    23,    'name':    'bob'}    

>>>    adict['age']    =    18    
>>>    print(adict)    
{'age':    18,    'name':    'bob'}    

>>> adict['phone']='15270203397'
>>> print adict
{'phone': '15270203397', 'age': 30, 'name': 'bob'}

1.1.4 删除字典

1. 通过del可以删除字典中的元素或整个字典
2. 使用内部方法clear()可以清空字典
3. 使用pop()方法可以“弹出”字典中的元素
>>>    del    adict['email’]    
>>>    print(adict)    
{'age':    22,    'name':    'bob’}    
>>>    adict.pop('age’)    
22    
>>>    print(adict)    
{'name':    'bob’}    
>>>    adict.clear()    
>>>    print(aDict)    
{}    

1.1.5 字典操作符

1. 使用字典键查找操作符[ ],查找键所对应的值
2. 使用in和not in判断键是否存在于字典中

>>>    adict    =    {'age':    18,    'name':    'bob'}    
>>>    print(adict['name’])    
 bob    
    
>>>    'bob'    in    adict    
False    
    
>>>    'name'    in    adict    
True    

1.2 字典相关函数

1.2.1 作用于字典的函数

1.  len():返回字典中元素的数目
2.  hash():本身不是为字典设计的,但是可以判断某个对象是否可以作为字典的键

>>>    print(adict)    
{'age':    23,    'name':    'bob’}    
>>>    print(len(adict))
2
>>>    hash(3)
3
>>>    hash([])     //list不能作为字典的键
Traceback    (most    recent    call    last):
        File    "<stdin>",    line    1,    in    <module>
TypeError:    unhashable    type:    'list'

1.2.2 字典内建方法

1. dict.copy():返回字典的一个副本

>>>    print(adict)    
{'age':    23,    'name':    'bob'}    
    
>>>    bdict    =    adict.copy()    
>>>    bdict['name']    =    'alice’    
>>>    print(adict)    
{'age':    23,    'name':    'bob'}    
    
>>>    print(bdict)    
{'age':    23,    'name':    'alice’}    

2. dict.get(key, default=None):对字典dict中的键
key,返回它对应的值value,如果字典中不存在此键,
则返回default的值
dict.get(key,    default=None):对字典dict中的键key,返回它对应的
值value,如果字典中不存在此键,则返回default的值    

>>> A=adict.get('AAA')
>>> 
 

3. dict.setdefault(key, default=None):如果字典中不存在key键,由dict[key]=default为它赋值

>>>    print(adict)    
{'age':    23,    'name':    'bob’}    
>>>    adict.setdefault('age',    20)    
23    
>>>    print(adict)    
{'age':    23,    'name':    'bob’}    
>>>    adict.setdefault('phone',    '15033448899’)    
'15033448899’    
>>>    print(adict)    
{'phone':    '15033448899',    'age':    23,    'name':    'bob’}    

4.字典常用函数

•  dict.items():返回一个包含字典中(键,值)对元组的列表
•  dict.keys():返回一个包含字典中键的列表
•  dict.values():返回一个包含字典中所有值的列表
•  dict.update(dict2):将字典dict2的键-值对添加到字典dict

案例1:模拟用户登陆信息系统
1.  支持新用户注册,新用户名和密码注册到字典中
2.  支持老用户登陆,用户名和密码正确提示登陆成功
3.  主程序通过循环询问进行何种操作,根据用户的选择,执行注册或是登陆操作

import getpass

userdb={}
def register():
    username=input('username: ')
    if username in userdb:
        print('%s is Aleary exists' % username)
    else:
        password=input('password: ')
        userdb[username]=password
def login():
    username = input('username: ')
    password=getpass.getpass('password: ')
    if userdb.get(username) != password:
        print('login failed!')
    else:
        print('login success!')
def show_menu():
    cmds={'0':register,'1':login}
    prompt="""(0) regist
(1) login
(2) quit
Please input you choice(0/1/2):"""
    while True:
        choice = input(prompt).strip()[0]
        if choice not in '012':
            print('Invalid choice.Try again')
            continue
        if choice == '2':
            break

        cmds[choice]()

if __name__ == '__main__':
    show_menu()

案例2:编写unix2dos的程序
1.  Windows文本文件的行结束标志是\r\n
2.  类unix文本文件的行结束标志是\n
3.  编写程序,将unix文本文件格式转换为windows文本文件的格式

import sys

def unix2dos(fname):
    dst_fname=fname+'.txt'
    with open(fname) as src_fobj:
        with open(dst_fname,'w') as dst_fobj:
            for line in src_fobj:
                dst_fobj.write(line.rstrip()+'\r\n')

if __name__ == '__main__':
    unix2dos(sys.argv[1])

案例3:编写类进度条程序
1.  在屏幕上打印20个#号
2.  符号@从20个#号穿过
3.  当@符号到达尾部,再从头开始

import time
import sys
for i in range (1,21):
    print('#',end='')
count=0

while True:
    print('\r%s@%s' % ('#'*count,'#'*(19-count)),end='')
    count+=1
    if count==20:
        count=0
    # sys.stdout.flush()
    time.sleep(0.1)

二、集合

2.1 创建集合

1. 数学上,把set称做由不同的元素组成的集合,集合(set)的成员通常被称做集合元素
2. 集合对象是一组无序排列的可哈希的值
3. 集合有两种类型
–  可变集合set
–  不可变集合frozenset
>>>    s1    =    set('hello')    
>>>    s2    =    frozenset('hello')    
>>>    s1    
{'l',    'e',    'o',    'h'}    
>>>    s2    
frozenset({'l',    'e',    'o',    'h'})    

2.2 集合类型操作符

1. 集合支持用in和not in操作符检查成员
2.  能够通过len()检查集合大小
3.  能够使用for迭代集合成员
4.  不能取切片,没有键

>>>    len(s1)    
4    
>>>    for    ch    in    s1:    
...            print(ch)    
l    
e    
o    
h    

5.  |:联合,取并集
6.  &:交集
7.  -:差补
>>>    s1    =    set('abc')    
>>>    s2    =    set('cde')    
>>>    s1    |    s2    
{'e',    'd',    'b',    'a',    'c'}    
>>>    s1    &    s2    
{'c'}    
>>>    s1    -    s2    
{'b',    'a'}    

2.3 集合内建方法

1. set.add():添加成员
2. set.update():批量添加成员
3. set.remove():移除成员

>>>    s1    =    set('hello')    
>>>    s1.add('new')    
>>>    s1    
{'h',    'o',    'l',    'e',    'new'}    
>>>    s1.update('new')    
>>>    s1    
{'h',    'o',    'l',    'w',    'e',    'new',    'n'}    
>>>    s1.remove('n')    
>>>    s1    
{'h',    'o',    'l',    'w',    'e',    'new'}    

2.4 集合内建方法

1. s.issubset(t):如果s是t的子集,则返回True,否则返回False
2.  s.issuperset(t):如果t是s的超集,则返回True,否则返回False
3  s.union(t):返回一个新集合,该集合是s和t的并集
4.  s.intersection(t):返回一个新集合,该集合是s和t的交集
5.  s.difference(t):返回一个新集合,该集合是s的成员,但不是t的成员

三、时间方法

3.1 time模块

3.1.1 时间表示方式

1.  时间戳timestamp:表示的是从1970年1月1日
00:00:00开始按秒计算的偏移量
2. UTC(Coordinated Universal Time,世界协调时)
亦即格林威治天文时间,世界标准时间。在中国为
UTC+8。DST(Daylight Saving Time)即夏令时
3. 元组(struct_time):由9个元素组成

3.1.2 time模块方法

https://yiyibooks.cn/  -> Python 352 文档 ->库参考

1. time.time():返回当前时间的时间戳

>>> time.time() 
1537452340.259848

2. time.sleep(secs):线程推迟指定的时间运行。单位为秒

>>> time.sleep(2)     //2s后
>>> 

3.time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为“Sun Jun 20 23:21:05 1993”的形式

>>> import time
>>> time.ctime()
'Thu Sep 20 22:05:17 2018'

4. time.strftime(format[, t]):把一个代表时间的元
组或者struct_time(如由time.localtime()和
time.gmtime()返回)转化为格式化的时间字符串。
如果t未指定,将传入time.localtime()

>>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
'2018-09-20 22:09:12'

3.2 datetime模块

3.2.1 datetime模块方法

1.使用datetime获取当前时间

>>> datetime.datetime.now()
datetime.datetime(2018, 9, 20, 22, 22, 40, 232542)  # 年月日时分秒毫秒

2.使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算

>>> from datetime import timedelta
>>> dt=datetime.datetime.now()
>>> days=timedelta(days=100,hours=3)
>>> dt+days
datetime.datetime(2018, 12, 29, 22, 25, 47, 777313)

四、异常处理

4.1 异常

4.1.1 什么是异常

异常就是程序在执行的过程中发生的错误

4.1.2 Python中的异常

异常 描述
NameError 未声明/初始化对象
IndexError 序列中没有没有此索引
SyntaxError 语法错误
KeyboardInterrupt 用户中断执行
EOFError 没有内建输入,到达EOF标记
IOError 输入/输出操作失败

4.1.3 try-except语句

定义了进行异常监控的一段代码,并且提供了处理异常的机制

>>>    try:    
...          data    =    int(input('input    a    number:    '))    
...    except    KeyboardInterrupt:    
...          print    'user    cancelled'    
...    except    ValueError:    
...           print('you    must    input    a    number!’)    
...    

4.1.4 else子句

•  在try范围中没有异常被检测到时,执行else子句
•  在else范围中的任何代码运行前,try范围中的所有代
码必须完全成功
>>>    try:    
...                    result    =    100    /    int(input("number:    "))    
...    except    Exception    as    e:    
...                    print('Error:',    e)    
...    else:    
...                    print(result)    
...    
number:    10    
10.0

4.1.5 finally子句

•  finally子句是无论异常是否发生,是否捕捉都会执行的一段代码
•  如果打开文件后,因为发生异常导致文件没有关闭,可能会发生数据损坏。使用finally可以保证文件总是
能正常的关闭

4.1.2 除法判断

1.  提示用户输入一个数字作为除数
2.  如果用户按下Ctrl+C或Ctrl+D则退出程序
3.  如果用户输入非数字字符,提示用户应该输入数字
4.  如果用户输入0,提示用户0不能作为除数

try:
    n=int(input('number: '))
    result=100/n

except (ValueError,ZeroDivisionError):
    print('Invalid Number')
except (KeyboardInterrupt,EOFError):
    print('\nBye')
else:       #异常不发生才执行
    print(result)
finally:    #不管异常是否发生,都会执行
    print('Done')

4.2 异常处理

4.2.1 raise语句

•  要想引发异常,最简单的形式就是输入关键字raise,
后面跟要引发的异常的名称
•  执行raise语句时,Python会创建指定的异常类的一
个对象
•  raise语句还可指定对异常对象进行初始化的参数

def set_age(name,age):
    if not  0<age<120:
        raise ValueError('age out of range.')
    print('%s:%s' % (name,age))

4.2.2  assert语句

•  断言是一句必须返回布尔值的语句
•  此外,发生异常也意味着表达式为假

>>>    assert    10    >    100,    "Wrong"    
Traceback    (most    recent    call    last):    
        File    "<stdin>",    line    1,    in    <module>    
AssertionError:    Wrong    

4.2.3 自定义异常

1. 编写第一个函数,函数接收姓名和年龄,如果年龄
不在1到120之间,产生ValueError异常
2. 编写第二个函数,函数接收姓名和年龄,如果年龄
不在1到120之间,产生断言异常

def set_age(name,age):
    if not  0<age<120:
        raise ValueError('age out of range.')
    print('%s:%s' % (name,age))

def set_age2(name,age):
    assert 0<age<120,'age out of range.'
    print('%s:%s' % (name,age))

if __name__ == '__main__':
    set_age('lijun',22)
    set_age2('zzx',200)

五、subprocess/pickle模块

5.1 os/subprocess模块

对文件系统的访问大多通过python的os模块实现

>>> import os
>>> os.system('ls /root')

call模块支持使用任何shell命令,可以通过call模块访问linux系统

from subprocess import call
call('ls /root/',shell=True)

5.2 pickle模块

5.2.1 pickle模块简介

1. 把数据写入文件时,常规的文件方法只能把字符串对
象写入。其他数据需先转换成字符串再写入文件 。
2. python提供了一个标准的模块,称为pickle。使用它
可以在一个文件中储存任何python对象,之后又可
以把它完整无缺地取出来

5.2.2 pickle模块方法

1. 分别调用dump()和load()可以存储、写入

>>>    import    pickle    as    p    
>>>    shoplistile    =    'shoplist.data'    
>>>    shoplist    =    ['apple',    'mango',    'carrot'] 
>>>    f    =    open(shoplistile,    'wb')
>>>    p.dump(shoplist,    f)
>>>    f.close()
>>>    
>>>    f    =    open(shoplistile)    
>>>    storedlist    =    p.load(f)    
>>>    print    storedlist    
['apple',    'mango',    'carrot']    

5.2.3 记账程序

1.  假设在记账时,有一万元钱
2.  无论是开销还是收入都要进行记账
3.  记账内容包括时间、金额和说明等
4.  记账数据要求永久存储

import os
import pickle as p
import time

def save_money(record,wallet):
    amount = int(input('amount: '))
    comment = input('comment: ')
    date = time.strftime('%Y-%m-%d')
    with open(wallet, 'rb') as fobj:
        balance = p.load(fobj) + amount
    with open(wallet, 'wb') as fobj:
        p.dump(balance, fobj)
    with open(record, 'a') as fobj:
        fobj.write(
            '%-15s%-8s%-8s%-8s%-20s\n' % (date, amount, '', balance, comment)
        )


def cost_money(record,wallet):
    amount = int(input('amount: '))
    comment = input('comment: ')
    date = time.strftime('%Y-%m-%d')
    with open(wallet, 'rb') as fobj:
        balance = p.load(fobj) + amount
    with open(wallet, 'wb') as fobj:
        p.dump(balance, fobj)
    with open(record, 'a') as fobj:
        fobj.write(
            '%-15s%-8s%-8s%-8s%-20s\n' % (date, amount, '', balance, comment)
        )


def query_money(record,wallet):
    print('%-15s%-8s%-8s%-8s%-20s' % ('date', 'save', 'cost', 'balance', 'comment'))
    with open(record) as fobj:
        for line in fobj:
            print(line, end='')
    with open(wallet, 'rb') as fobj:
        print('Latest Balance: %s' % p.load(fobj))

def show_menu():
    record='/tmp/record.txt'
    wallet='/tmp/wallet.txt'
    cmds={'1':save_money,'2':cost_money,'3':query_money}
    prompt='''*******欢迎使用记账小程序*******
1.save money
2.cost money
3.query money
4.quit
请输入序号(1/2/3/4):'''
    if not os.path.exists(wallet):
        with open(wallet,'wb') as fobj:
            p.dump(10000,fobj)

    while True:
        choice=input(prompt).strip()[0]
        if choice not in '1234':
            print('Invalid choice Try again')
            continue
        if choice == '4':
            break
        cmds[choice](record,wallet)

if __name__ == '__main__':
    show_menu()

猜你喜欢

转载自blog.csdn.net/qq_36441027/article/details/82792679