Python之路,week02 - Python基础2

本节内容

  1. 列表、元组操作
  2. 元组与购物车程序练习
  3. 字符串常用操作
  4. 字典的使用
  5. 三级菜单实例
  6. 集合及其运算
  7. 文件读与写详解
  8. 文件修改详解
  9. 字符编码转换详解

1. 列表、元组操作

names = ["ZY","GY","XP","XL"]   #定义列表

print(names)
print(names[0],names[2])        #通过下标访问列表中的元素,下标从0开始计数

print(names[1:3])      #切片:取多个元素  
print(names[-1])       #切片:取多个元素 
print(names[-3:-1])    #切片:取多个元素

names.append("LH")     #追加

names.insert(1,"CR")   #插入

names[2] = "XD"     #修改

#删除3种
names.remove("CR")
del names[1]
names.pop(1)     #如果不输入下标,默认删最后一位

print(names.index("XD"))    #查询下标
print(names.count("XD"))    #统计

names.reverse()     #反转
names.sort()    #排序

names2 = [1,2,3,4]
names.extend(names2)    #扩展

注:copy真的这么简单么!?

names = ["ZY","GY",["a","b"],"XP","XL"]   #定义列表
names2 = names.copy()
print(names,names2)

names[1] = "GY1"
names[2][0] = "a1"
print(names,names2)

输出:
['ZY', 'GY', ['a', 'b'], 'XP', 'XL'] ['ZY', 'GY', ['a', 'b'], 'XP', 'XL']
['ZY', 'GY1', ['a1', 'b'], 'XP', 'XL'] ['ZY', 'GY', ['a1', 'b'], 'XP', 'XL']

结论:copy是浅拷贝,只拷贝数组第一层!!

解决:导入copy模块,用deepcopy

import copy

names = ["ZY","GY",["a","b"],"XP","XL"]   #定义列表
names2 = copy.deepcopy(names)
print(names,names2)

names[1] = "GY1"
names[2][0] = "a1"
print(names,names2)
names = ["ZY","GY",["a","b"],"XP","XL"]   #定义列表

print(names[0:-1:2])    
print(names[::2])

for i in names:     #循环输出列表
    print(i)

补充:实现浅copy的三种方式

import copy

person = ['name',['a',100]]

p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)

2. 元组与购物车程序练习

元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index,完毕。  

程序练习

请闭眼写出以下程序。

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额

product_list = [
    ("iphone",5800),
    ("Mac Pro",12000),
    ("Starbuk Lattle",31),
    ("Alex Python",81),
    ("Bike",800)
]

shopping_list = []

salary = input("Input your salary:")
if salary.isdigit():
    salary = int(salary)
    while True:
        '''
        #打印下标+商业列表,法一:
        for item in product_list:
            print(product_list.index(item),item)
        '''
        # 打印下标+商业列表,法二:
        #enumerate==>取出列表下标
        for index,item in enumerate(product_list):
            print(index,item)
        user_choice = input("Please input your choice>>:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice < len(product_list) and user_choice>= 0:
                p_item = product_list[user_choice]
                if p_item[1] <= salary: #买得起
                    shopping_list.append(p_item)
                    salary -= p_item[1]
                    print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary))
                else:
                    print("\033[41;1m你的余额只剩[%s]了,买毛线啊!\033[0m" %(salary))
            else:
                print("商品不存在")
        elif user_choice == 'q':
            print("-------shopping list--------")
            for p in shopping_list:
                print(p)
            print("your current balance is:",salary)
            exit()
        else:
            print("invalid option")

3. 字符串常用操作

name = "my name is lemon"

print(name.capitalize())    #首字母大写
print(name.count("l"))      #统计l出现次数
print(name.center(50,"-"))  #一共打50个字符,name放中间
print(name.endswith("on"))  #判断是否以on结尾
print("lem\ton".expandtabs(tabsize=30))     #将\t转换成多长的空格
print(name.find("a"))       #查找y,找到返回其索引,找不到返回-1
print(name[name.find("a"):])    #字符串切片

name2 = "my name is {name},i'm {age} years old"
print(name2.format(name="LM",age=20))
print(name2.format_map({'name':"LM",'age':20}))

print('ab123'.isalnum())    #英文字符+数字
print('ab123'.isalpha())    #纯英文字符
print('1A'.isdecimal())     #十进制
print('123'.isdigit())      #整数
print('ab123'.isidentifier())   #判断是不是合法的标识符(变量名)
print('ab123'.islower())    #小写
print('ab123'.isupper())    #大写
print('ab123'.isnumeric())  #数字
print('My Name Is'.istitle())   #首字母大写
print('&'.join(['a','b','c','d']))
print(name.ljust(50,'-'))       #长度50,不足-补上,左
print(name.rjust(50,'-'))       #长度50,不足-补上,右
print('My Name Is'.lower())     #变小写
print('My Name Is'.upper())     #变大写
print('\n    ab123'.lstrip())   #去除左边的回车和空格
print('ab123    \n'.rstrip())       #去除右边的回车和空格
print('       ab123\n'.strip())     #去除所有的回车和空格

p = str.maketrans("abcde","12345")  #字符替换
print("abdwbfr".translate(p))

print('aab123'.replace('a','A',1))  #替换
print('aab123'.rfind('a'))          #查找返回最右边的下标
print('1+2+3+4'.split('+'))         #把字符串按'+'分成列表
print('My Name Is'.swapcase())      #交换大小写
print('my name is'.title())         #首字母变大写

4. 字典的使用

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

语法:

#key:value
info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}

字典的特性:

  • 字典是无序的,,因为没下标
  • key必须是唯一的,so 天生去重

增加、修改

info["stu1104"] = "苍井空"

删除

info.pop("stu1101")     #标准删除姿势
del info['stu1103']     #换个姿势删除
info.popitem()          #随机删除

查找

>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> 
>>> "stu1102" in info       #标准用法
True
>>> info.get("stu1102")     #获取
'LongZe Luola'
>>> info["stu1102"]         #同上,但是看下面
'LongZe Luola'
>>> info["stu1105"]         #如果一个key不存在,就报错,get不会,不存在只返回None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stu1105'

多级字典嵌套及操作

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"
print(av_catalog["大陆"]["1024"])
#ouput 
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

其它姿势

#values 查询值
>>> info.values()
dict_values(['LongZe Luola', 'XiaoZe Maliya'])

#keys   查询键
>>> info.keys()
dict_keys(['stu1102', 'stu1103'])

#setdefault     查询key,若有则不变,若无则新建并传值
>>> info.setdefault("stu1106","Alex")
'Alex'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> info.setdefault("stu1102","龙泽萝拉")
'LongZe Luola'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}


#update     合并2个字典,若key存在则更新,若不存在则新建
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
>>> info.update(b)
>>> info
{'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}

#items      把字典转换为一个列表
info.items()
dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])


#通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
>>> dict.fromkeys([1,2,3],'testd')
{1: 'testd', 2: 'testd', 3: 'testd'}

循环dict

#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items():    #会先把dict转成list,数据里大时莫用
    print(k,v)

5. 三级菜单实例

data = {
    '北京':{
        '海淀':{
            '五道口':{'soho','网易','google'},
            '中关村':{'爱奇艺','汽车之家','youku'},
            '上地':{'百度'},
        },
        '昌平':{
            '沙河':{'老男孩','北航'},
            '天通苑':{'链家','我爱我家'}
        },
    },
    '山东':{
        '德州':{},
        '青岛':{},
        '济南':{},
    },
    '广东':{
        "东莞":{},
        "常熟":{},
        "佛山":{},
    },
}

exit_flag = False

while not exit_flag:
    for i in data:
        print(i)

    choice = input("选择进入1>>:")
    if choice in data:
        while not exit_flag:
            for i2 in data[choice]:
                print("\t",i2)
            choice2 = input("选择进入2>>:")
            if choice2 in data[choice]:
                while not exit_flag:
                    for i3 in data[choice][choice2]:
                        print("\t\t", i3)
                    choice3 = input("选择进入3>>:")
                    if choice3 in data[choice][choice2]:
                        for i4 in data[choice][choice2][choice3]:
                            print("\t\t",i4)
                        choice4 = input("最后一层,按b返回>>:")
                        if choice4 == "b":
                            pass
                        elif choice4 == "q":
                            exit_flag = True
                    if choice3 == "b":
                        break
                    elif choice3 == "q":
                        exit_flag = True
                if choice2 == "b":
                    break
                elif choice2 == "q":
                    exit_flag = True

6. 集合及其运算

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)    #创建一个数值集合
t = set("Hello")        #创建一个唯一字符的集合

list_2 = set([2,6,0,66,22,8,4])
list_3 = set([1,3,7])
list_4 = set([5,6,7,8])
print(list_1,list_2)

#交集
print(list_1.intersection(list_2))

#没有交集
print(list_3.isdisjoint(list_4))

#并集
print(list_1.union(list_2))

#差集     in list_1 but not in list_2
print(list_1.difference(list_2))

#子集
print(list_3.issubset(list_1))

#父集
print(list_1.issuperset(list_3))

#对称差集   (项在1或2中,但不会同时出现在二者中)
print(list_1.symmetric_difference(list_2))

#------------符号表示--------------
print(list_1 & list_2)  #交集
print(list_1 | list_2)  #并集
print(list_1 - list_2)  #差集
print(list_1 ^ list_2)  #对称差集

#基本操作:
list_1.add('x')         #添加一项
print(list_1)
list_1.update([10, 37, 42])     #在s中添加多项
print(list_1)

list_1.remove('x')      #删除一项
list_1.pop()        #随机弹出一个
list_1.discard('x')     #指定删除,若不存在返回none
print(len(list_1))      #set的长度

x in s  
#测试 x 是否是 s 的成员  
  
x not in s  
#测试 x 是否不是 s 的成员  
  
s.issubset(t)  
s <= t  
#测试是否 s 中的每一个元素都在 t 中  
  
s.issuperset(t)  
s >= t  
#测试是否 t 中的每一个元素都在 s 中  
  
s.copy()  
#返回 set “s”的一个浅复制  


7. 文件读与写详解

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

现有文件如下

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂

基本操作:

f = open("yesterday",'r',encoding="utf-8")  #打开文件,,f==>文件句柄,其中r为读模式,w为写,只能2选一,蠢死了
print(f.read())     #此时读完文件,光标位置在文件最后一行
f.close()      #关闭

f2 = open("yesterday2",'w',encoding="utf-8")
f2.write("12345,\n")
f2.write("山上打老虎")

f2 = open("yesterday2",'a',encoding="utf-8")    #a = append 追加,,,也不能读
f2.write("yyyyyyyyyyyyyyy")
print("--read",f2.read())

小程序:进度条

import sys,time

for i in range(50):
    sys.stdout.write("#")
    sys.stdout.flush()      #写入磁盘
    time.sleep(0.1)         #延时

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读; 不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

循环输出文件方法,每行输出

'''
#low    炸内存
for index,line in enumerate(f.readlines()):
    if index == 9:
        print('----------------------------')
    print(line)
'''

#high   内存里只存一行
count = 0
for line in f:
    if count == 9:
        print('$$$$$$$$$$$$$$$$$$$$$$$$$$$')
    print(line)
    count += 1

其他语法:

def close(self): # real signature unknown; restored from __doc__
        """
        Close the file.
        
        A closed file cannot be used for further I/O operations.  close() may be
        called more than once without error.
        """
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        """ Return the underlying file descriptor (an integer). """
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        """ True if the file is connected to a TTY device. """
        pass

    def read(self, size=-1): # known case of _io.FileIO.read
        """
        注意,不一定能全读回来
        Read at most size bytes, returned as bytes.
        
        Only makes one system call, so less data may be returned than requested.
        In non-blocking mode, returns None if no data is available.
        Return an empty bytes object at EOF.
        """
        return ""

    def readable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a read mode. """
        pass

    def readall(self, *args, **kwargs): # real signature unknown
        """
        Read all data from the file, returned as bytes.
        
        In non-blocking mode, returns as much as is immediately available,
        or None if no data is available.  Return an empty bytes object at EOF.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        """ Same as RawIOBase.readinto(). """
        pass #不要用,没人知道它是干嘛用的

    def seek(self, *args, **kwargs): # real signature unknown
        """
        Move to new file position and return the file position.
        
        Argument offset is a byte count.  Optional argument whence defaults to
        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
        are SEEK_CUR or 1 (move relative to current position, positive or negative),
        and SEEK_END or 2 (move relative to end of file, usually negative, although
        many platforms allow seeking beyond the end of a file).
        
        Note that not all file objects are seekable.
        """
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        """ True if file supports random-access. """
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        """
        Current file position.
        
        Can raise OSError for non seekable files.
        """
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        """
        Truncate the file to at most size bytes and return the truncated size.
        
        Size defaults to the current file position, as returned by tell().
        The current file position is changed to the value of size.
        """
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a write mode. """
        pass

    def write(self, *args, **kwargs): # real signature unknown
        """
        Write bytes b to file, return number written.
        
        Only makes one system call, so not all of the data may be written.
        The number of bytes actually written is returned.  In non-blocking mode,
        returns None if the write would block.
        """
        pass

with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass

8. 文件修改详解

文件修改思路:
1、把文件读在内存,在内存里修改,写入硬盘
2、建立一个新文件,修改后写入新文件

f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")

for line in f:
    if "conversation" in line:
        line = line.replace("conversation","CONVERSATION")
    f_new.write(line)

f.close()
f_new.close()

9. 字符编码转换详解

需知:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

上图仅适用于py2

posted @ 2017-08-11 22:33  柠檬红茶cc  阅读(655)  评论(0编辑  收藏  举报