目录

使用字典完成一个点餐系统

要求

判断两个函数的区别

lambda,reduce的应用

reduce,map,filter,sorted的应用

按照字典的值进行排序

Python中的类,实例,封装,继承和多态

Python中的内置模块和第三方模块

自定义一个包

打印函数的执行时间

isinstance的应用

hasattr(),setattr(),getattr()的作用

对类中绑定的属性做一个限制

鸭子类型

import re :正则——指定规则,抽取数据/过滤,筛选数据


使用字典完成一个点餐系统

要求

  1. 实现一级菜单和二级菜单的展示,选择对应序号可以由一级菜单进入二级菜单
  2. 建立购物车,当有用户选择二级菜单菜品时,可以输入数量购买多个,购买的菜品及数量记录到购物车中
  3. 进入到二级菜单可以再切换到一级菜单,在一级菜单和二级菜单度都可以打印出购物车信息
  4. 无论是在一级菜单下还是二级菜单下都可以进行结算,结算时打印出购物车中的数据
def show_shop_car(shop_car):n = 1dicts = {}print('序号 商品名称 商品单价 商品数量 商品总价')total_price = 0for goods_name, goods_info in shop_car.items():goods_price = goods_info[1]goods_num = goods_info[0]per_price = goods_info[2]print('{}     {}    {}元      {}    {}元'.format(n, goods_name, goods_price, goods_num,per_price).center(len('序号 商品名称 商品单价 商品数量 商品总价'), ' '))total_price+=per_pricedicts[n] = goods_namen+=1print('总价:{}元'.format(total_price))return dicts
def input_option(values,shop_cars):if values == 'q':show_shop_car(shop_cars)global flag1flag1 = 2elif values == 'w':returnelif values == 'c':goods_name_to_goods_info = show_shop_car(shop_cars)change_choice1 = int(input('选择要修改的商品序号'))goods_name = goods_name_to_goods_info[change_choice1]goods_info = shop_cars[goods_name]change_choice2 = int(input('修改输入1 删除输入2'))global shop_carif change_choice2==1:change_choice2 = int(input('输入购买数量'))goods_info[0] = change_choice2goods_info[2] = change_choice2*goods_info[1]shop_car[goods_name] = goods_infoelif change_choice2==2:shop_car.pop(goods_name)return 2else:return 1dicts = {'1':{'主食':{'包子':1,'鳗鱼饭':10,'拉面':12,'清汤挂面':4}},'2':{'凉菜':{'天妇罗':5,'寿司':2,'皮蛋豆腐':3,'雷焦茄子':3,'三色丸子':1}},'3':{'热菜':{'蛋包饭':10,'火锅':20,'大阪烧':11,'炸猪排':13,'八珍豆腐':100}}
}
shop_car = {}
flag1 = 1while flag1 == 1:for num,second_dict in dicts.items():print(num,list(second_dict.keys())[0])choice_first_menu = input('请选择序号 q 结算退出c查看购物车并修改')result = input_option(choice_first_menu, shop_car)if not result or result==2:continuethird_dict=list(dicts[choice_first_menu].values())[0]n = 1choice_to_dict = {}for goods_name,goods_price in third_dict.items():print(n, goods_name, goods_price, '元')choice_to_dict[n]=goods_namen+=1while True:choice_second_menu = input('请选择序号 q 结算退出 w 返回上级 c查看购物车并修改')result = input_option(choice_second_menu, shop_car)if not result:breakelif result==2:continuechoice_second_menu = int(choice_second_menu)goods_name = choice_to_dict[choice_second_menu]goods_price=third_dict[goods_name]goods_num = int(input('请输入购买数量'))shop_car.update({goods_name:[goods_num,goods_price,goods_num*goods_price]})print('购买成功')

判断两个函数的区别

def hello():def aaa(j):def bbb():return j**jreturn bbb()f = []for i in range(1,4):f.append(aaa(i))return f
f1,f2,f3 = hello()
print(f1,f2,f3)
结果
1 4 27def world():f = []for i in range(1,4):def aaa():return i*if.append(aaa)return f
f1,f2,f3 = world()
print(f1(),f2(),f3())
结果
9 9 9注:在world()函数中,调用f1()或f2()或f3()的过程中,最初循环所得出的结果3在最开始就已经赋值给了f的列表,之后才调用aaa()这个函数,所以得出的结果都是9;在hello()函数中,首先定义的是aaa()的函数,之后每循环一遍将i的值传递一遍,得出的结果才是1,2,27.

lambda,reduce的应用

hello = lambda x,y:x+y
print(hello(4,8))
结果
12
def hello(x,y):return x+y
print(hello(4,8))
结果
12
from functools import reduce
result = reduce(hello,range(10))
print(result)
结果
45注:lambda一般当代码不需要重复调用时可以使用,和hello(x,y)的函数除了形式不同几乎没有区别,写起来比较省事,也可以减少一些函数名的重复。reduce函数将range中的值传到hello中重复调用,得出0到9的和。

reduce,map,filter,sorted的应用

一、reduce1.在python3中,内置函数中已经没有reduce了。要使用reduce,需要从functools模块里引入2.作用对序列中的元素进行累积3.返回值返回函数的计算结果二、map1.map是python内置函数,会根据提供的函数对指定的序列做映射三、filterfilter函数是Python中常用的内置函数,主要用来根据特定条件过滤迭代器中不符合条件的元素,返回一个惰性计算的filter对象或迭代器:filter(function or None, iterable)function:函数,作用是对iterable中的每个元素判断是否符合特定条件。None:不调用任何函数,只对可迭代对象中的元素本身判断真假,保留为真的元素。iterables:可迭代对象(序列、字典等)。#取出范围内的偶数
o = lambda x:x%2 == 0
print(list(filter(o,range(1,10))))结果
[2, 4, 6, 8]四、sortedsorted()函数:返回一个排序后的新序列,不改变原始序列。dicts = {'hello1':'1','hello2':'4','hello3':'3','hello4':'8','hello5':'2'}
lists = [2,4,562,1,5,7,31,6,7]
print(sorted(lists))#排序,返回一个新的值
lists.sort(reverse=True)#改变之前的值
print(lists)结果
[1, 2, 4, 5, 6, 7, 7, 31, 562]
[562, 31, 7, 7, 6, 5, 4, 2, 1]

按照字典的值进行排序

方法一:
dicts = {'hello1':'1','hello2':'4','hello3':'3','hello4':'8','hello5':'2'}
a1 = sorted(dicts.items(), key=lambda x: x[1])
print(a1)结果
[('hello1', '1'), ('hello5', '2'), ('hello3', '3'), ('hello2', '4'), ('hello4', '8')]方法二:
dicts = {'hello1':'1','hello2':'4','hello3':'3','hello4':'8','hello5':'2'}
dict1 = {}
d = {}
for a,b in dicts.items():dict1.update({b:a})
for i in sorted(dict1):d.update({dict1[i]:i})
print(d)
#通过交换字典中的键和值来进行比较
结果
[('hello1', '1'), ('hello5', '2'), ('hello3', '3'), ('hello2', '4'), ('hello4', '8')]

Python中的类,实例,封装,继承和多态

类:类中面向对象编程中的重要概念,一类具体相同属性和行为的事物可以称为类,类可以实例化为单个的对象。

类中包含属性和方法:

  1. 属性:描述一个物体
  2. 方法:定义在类中的函数,动态,描述一个物体的特性

实例化

  1. 实例:具体到一个实体
  2. 化:根据类生成一个实例

例1:

class student(object):def __init__(self,name,score):#对象属性,实例属性self.name = nameself.score = scoredef show_score(self):print(self.score)#stu1就变成了调用类的实例
stu1 = student('王小明',100)
print(stu1.name)
print(stu1.score)
stu2 = student('王小二',99)
print(id(stu2),id(stu1))结果
王小明
100
1511563495072 1511563494736

例2:

#定义一个动物类
class Animal(object):def eat(self):print('i like food')
#定义一个动作类
class Runnable(object):def run(self):print('i can run')
#定义一个动作类
class FLYable(object):def fly(self):print('i can fly')
#定义一个物种属性类
class Mammal(object):def show_type(self):print('i am Mammal')
#定义一个物种属性类
class Ovipara(object):def show_type(self):print('i am Ovipara')
#定义一个Dog类,继承动物类,一个动作类和一个物种属性类——多继承:继承多个父类
class Dog(Animal,Runnable,Mammal):def eat(self):print('i like meat')
#定义一个Cat类,继承动物类——单继承:继承一个父类
class Cat(Animal):def eat(self):print('i like fish')dog1 = Dog()#实例化
dog1.eat()#如果子类中有方法则直接调用,否则调用父类的方法
cat1 = Cat()#实例化
cat1.eat()
dog1.run()#调用父类Runnable中的方法
dog1.show_type()#调用父类Mammal中的方法结果
i like meat
i like fish
i can run
i am Mammal

例3:

class Student:#类属性——可以被类直接调用num = 0  # 存储放到外边,触发事件放到里面,不然值保留不住def __init__(self,name,score,age):#对象属性,实例属性self.name = nameself.score = scoreself.__age = age#添加上__对外界来说相当于把属性隐藏了起来,变成了私有属性,类不能直接调用私有属性Student.num+=1#每一次实例化后num加1def show_level(self):level = '优' if self.score>90 else '良'if self.score>80 and self.score<90 else '及格'return levelstu = Student('王小明',100,53)
print(stu.name)
print(stu.show_level())
print(stu.num)
stu1 = Student('王小明',100,53)
print(stu1.show_level())
print(stu1.num)结果
王小明
优
1
优
2注:虽然实例化后无法调用封装好的私有属性,但可以通过调用封装好的私有方法来调用封装好的私有属性。

Python中的内置模块和第三方模块

模块就是一个实现某种业务的工具包,要使用工具包中的工具,就需要导入这个模块:

  1. import 【模块名】,本质上就是在一个python文件中引入另一个python文件
  2. 引入的模块还可以在文档中设置别名:import 【模块名】 as 【别名】
  3. 引入复杂模块的一部分 from 【模块名】 import 【子模块】

模块分为:内置模块——比如random,datetime,第三方模块——需要下载才能引入

Python第三方模块的安装方法:

  1. 直接打开cmd,输入命令。
  2. pip工具升级:   python -m pip install --upgrade pip
  3. 安装模块:  pip install 【模块名】
  4. 卸载模块:pip uninstall 【模块名】

例:

#导入模块:
import time
from string import punctuation as pt,whitespace as wh #简化为别名pt,wh
import datetime
import os
import reprint(time.time())
strs = 'ncjkkdsndla\n12314kj   nkdc\tjc01!#$#@%1adse234'
print(string.punctuation)#打印引用的特殊字符
print(pt)
lists = ''.join([x for x in strs if x not in pt + wh])#这里使用了字符串拼接''.join
print(lists)
print(os.getcwd())#找到文件目录
print(os.path.isdir('1016day3.py'))#判断是否是一个文件夹
print(os.path.isfile('1016day3.py'))#判断是否是一个文件
print(os.listdir())#找出当前路径下所有文件
print([x for x in os.listdir() if x.endswith('.py')])#找出文件后缀为.py的文件结果
1666698427.1523108
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
ncjkkdsndla12314kjnkdcjc011adse234
C:\Users\LENOVO\Desktop\python
False
True
['1015day2.py', '1016day3.py', '1021.py', '1021.rar', '1023.py', '1023day5.py', '5 day.py', 'day1(1).py', 'dicts.py', '菜单系统(1).py']
['1015day2.py', '1016day3.py', '1021.py', '1023.py', '1023day5.py', '5 day.py', 'day1(1).py', 'dicts.py', '菜单系统(1).py']

例2:

引入第三方模块xpinyin:pip install xpinyin
#汉字转化成拼音from xpinyin import Pinyin
p = Pinyin()
print(p.get_pinyin('中国',' '))结果
zhong guo

自定义一个包

找到安装python的目录,进入到lib下的site-packages文件夹下新建一个myfile(自定义名字)的文件夹,进入到其中,新建两个.py文件:__init__.py和(自定义名称).py

例:

class Student:@classmethod#装饰器,给函数加一个能被类调用的特性,不需要实例化也可以调用def say_hello(self):print('hello')@classmethoddef run(self):print('i can run')@classmethoddef get_data(self,n):#定义一个斐波那契数列的方法x,y = 0,1for i in range(n):x,y = y,x+yyield xfrom myfile.hahaha import Student
Student.run()
Student.say_hello()
#打印出斐波那契数列
for i in Student.get_data(10):print(i)结果
i can run
hello注:装饰器,在不改变原函数的基础上,给函数增加新的东西

打印函数的执行时间

def hello():begin = time.time()time.sleep(3)print(123)stop = time.time()print(stop-begin)#打印执行时间
hello()
print(hello.__name__)#打印函数名结果
123
3.0101311206817627
hellodef log(func):def wrapper(*args,**kwargs):begin = time.time()f = func(*args,**kwargs)stop = time.time()print(stop-begin)return freturn wrapper
print(log(hello()))
#打印出来的是log()返回的函数wrapper本身,再加上()之后调用的就是函数里的方法
log(hello)()
#调用wrapper函数的方法,因为返回的值是f,而f又调用func参数,hello的值又付给了func参数,所以这里调用了hello的方法#简化调用,功能和log(hello)()相当
@log
def hello():begin = time.time()time.sleep(3)print(123)
hello()结果
123
3.013305425643921
<function log.<locals>.wrapper at 0x00000282D818B1F0>
123
3.0073184967041016
3.0073184967041016
123
3.003321647644043

isinstance的应用

class Dog:passclass YellowDog(Dog):def __init__(self):#绑定一个类型self.x = 9
y = YellowDog()
print(isinstance(y,YellowDog))#确定y是YellowDog的实例化对象
print(isinstance(y,Dog))#确定y是Dog的实例化对象d = Dog()
print(isinstance(d,YellowDog))
print(isinstance(d,Dog))print(isinstance([1,2,3,4],list))#判断某一个东西是否是某种类型结果
True
True
False
True
True

hasattr(),setattr(),getattr()的作用

class Dog:passclass YellowDog(Dog):def __init__(self):#绑定一个类型self.x = 9
y = YellowDog()
d = Dog()print(hasattr(y,'x'))#看看实例化对象中有没有x
print(hasattr(y,'yy'))#实例化对象中没有yy
setattr(y,'yy',20)#给yy绑定了一个属性
print(hasattr(y,'yy'))#实例化对象中有了yy
print(getattr(y,'yy'))#获取属性结果
True
False
True
20

对类中绑定的属性做一个限制

class Student(object):__slots__ = ('name','score','age')#对绑定的属性做了一个限制,但是可以经过子类解除限制
stu1 = Student()
stu1.age = 12#实例化后可以随便绑定属性
print(stu1.age)
stu1.address = 12#显示无法绑定这个属性结果
AttributeError: 'Student' object has no attribute 'address'
12class Student1(Student):pass
stu2 = Student1()
stu2.address = 2222
print(stu2.address)#不能加address的限制在子类中不受影响
结果
2222#对年龄做一个限制
class Student:def set_age(self,age):if age>150 or age<0:raise ValueError('年龄不符合要求')#给年龄做了一个限制else:self.__age = agedef show_age(self):print(self.__age)
stu = Student()
stu.set_age(160)
stu.show_age()结果
ValueError: 年龄不符合要求class Student:@property#绑定一个age属性def age(self):return self._age@age.setter#设置属性限制,怎么去修改这个属性def age(self,vlaue):if vlaue >150 or vlaue<0:raise ValueError('age在0到150之间')self._age = vlauestu = Student()
stu.age = 169
print(stu.age)结果
ValueError: age在0到150之间

鸭子类型

def run_twice(animal):#这里面的方法不允许修改,但是可以根据它给的方法添加更多的类animal.run()animal.run()class Dog:def run(self):print('dog is running')
class Cat:def run(self):print('Cat is running')dog1 = Dog()
cat1 = Cat()
run_twice(dog1)
run_twice(cat1)结果
dog is running
dog is running
Cat is running
Cat is running注:只要定义的类中含有run()方法,都可以调用run_twice()函数

import re :正则——指定规则,抽取数据/过滤,筛选数据

\w:数字,字母,下划线,汉字
\s:匹配所有的特殊字符
\d:匹配数字
\D:
^:取反
*:零个或多个
.:代表除了换行之外的所有元素
+代表一个或多个
模式,贪婪模式/非贪婪模式(默认是贪婪模式)

例:

strs = 'ncjkkdsndla\n12314kj   nkdc\tjc01好人!#$#@%1adse234'
result = ''.join(re.findall('\w+',strs))
print(result)result =re.findall('\w+?',strs)#非贪婪模式,匹配的值比较散
print(result)result =re.findall('\s+',strs)
print(result)strs = 'ncjkkdsndla\n12314kj   nkdc\tjc01是个好人!#$#@%1adse234'
result = ''.join(re.findall('[a-zA-Z]+',strs))#自己在[]中指定规则
print(result)
strs = 'ncjkkdsndla\n12314kj   nkdc\tjc01是个好人!#$#@%1adse234'
result = ''.join(re.findall('[^a-zA-Z]+',strs))#^取反
print(result)result =re.findall('\w{2,4}',strs)#取范围
print(result)result =re.findall('  (\w+)c\t',strs)#截取部分元素
print(result)结果
ncjkkdsndla12314kjnkdcjc01好人1adse234
['n', 'c', 'j', 'k', 'k', 'd', 's', 'n', 'd', 'l', 'a', '1', '2', '3', '1', '4', 'k', 'j', 'n', 'k', 'd', 'c', 'j', 'c', '0', '1', '好', '人', '1', 'a', 'd', 's', 'e', '2', '3', '4']
['\n', '   ', '\t']
ncjkkdsndlakjnkdcjcadse12314    01是个好人!#$#@%1234
['ncjk', 'kdsn', 'dla', '1231', '4kj', 'nkdc', 'jc01', '是个好人', '1ads', 'e234']
['nkd']Process finished with exit code 0

大数据Python基础学习——练习(二)相关推荐

  1. 大数据Python基础学习——练习(一)

    目录 水仙花数的程序编写 求列表中的最大值和最小值 斐波那契数列的程序编写 用自己的代码实现Strip()的功能 编写程序对列表中的元素去重 统计列表中每个元素出现的个数 九九乘法表 选出两个列表中对 ...

  2. Python基础学习(二)-条件,循环语句

    Python基础学习(二)-条件,循环语句     一,条件语句    1,if  else           if  判断条件:               执行语句...           e ...

  3. 大数据之spark学习记录二: Spark的安装与上手

    大数据之spark学习记录二: Spark的安装与上手 文章目录 大数据之spark学习记录二: Spark的安装与上手 Spark安装 本地模式 Standalone 模式 基本配置 步骤1: 复制 ...

  4. 干货分享 | 大数据零基础学习路线:新手从入门到精通

    很多初学者在萌生向大数据方向发展的想法之后,不免产生一些疑问,应该怎样入门?应该学习哪些技术?学习路线又是什么? 所有萌生入行的想法与想要学习Java的同学的初衷是一样的.岗位非常火,就业薪资比较高, ...

  5. 大数据Python基础——第三章 字符串加列表练习

    目录 字符串 列表 字符串 一.什么是字符串 字符串或串(String)是由数字.字母.下划线组成的一串字符:它是编程语言中表示文本的数据类型:Python程序中的字符串在计算机内存中,统一使用uni ...

  6. 大数据Python基础——第一章 搭建环境

    一. 从百度Python官网处下载最新版或者其他版本的Python软件. 1.附下载链接:Download Python | Python.orgThe official home of the Py ...

  7. python基础学习(二)注释和算术运算符

    注释 1. 注释的作用 注释就是对某些代码进行标注说明,以增强代码的可读性.我们在写程序的时候,编写的某一部分代码的意图不太明显,这时候就需要对这一部分代码加以说明,来明确这一部分到的意图.一般的编程 ...

  8. python | 基础学习(一)了解Bug、pycharm、变量、程序的三大流程(顺序、if、while)、运算符、快捷键

    文章目录 一.引言 1.python的起源 2.解释器 3.python的设计目标 4.python的特点 二.python 1.了解BUG 2.python的三种运行方式 ①解释器python/py ...

  9. python大数据零基础_零基础学习大数据人工智能,学习路线篇!

    大数据处理技术怎么学习呢?首先我们要学习Python语言和Linux操作系统,这两个是学习大数据的基础,学习的顺序不分前后. Python:Python 的排名从去年开始就借助人工智能持续上升,现在它 ...

最新文章

  1. Openstack组件部署 — Keystone Install Create service entity and API endpoints
  2. java可以入侵电脑系统吗_如何通过tomcat入侵远程计算机系统
  3. java第一份工作_Java 学到什么程度可以找到第一份工作 ?
  4. 配置审计(Config)配合开启OSS防盗链功能
  5. 简单的文本设计就能影响游戏体验?游戏中提升玩家体验的小设计
  6. C语言学习之求一个3×3的整型矩阵对角线元素之和
  7. libcoredb.class.php,ThinkPHP/Lib/Core/Db.class.php中pdo处理逻辑似乎不完善,导致config中pdo配置失效...
  8. php中mimes函数,wordpress函数check_upload_mimes()用法示例
  9. Node.js「三」—— 创建静态 WEB 服务器
  10. mysql数据库5.7配置文件_mysql数据库5.7版本部署
  11. JavaScript 读取地址栏参数
  12. 嵌入式c语言移植,嵌入式c语言位操作的移植与优化.doc
  13. 关于@NotNull 和 @Nullable
  14. 免费rar密码破解工具排行榜
  15. 曲线绕x轴旋转曲面方程_曲线绕着Ox轴旋转所得的曲面方程是______。
  16. 330pics-shell scripts-second
  17. 【HCIE-RS 天梯路】STP RSTP MSTP
  18. 信息系统项目管理10大管理
  19. 路由宝刷华硕rt-n14u_如何在2019年取消硬砖路由器的砖块化(以华硕RT-N16为例)
  20. 搭建开发环境 | 工欲善其事,必先利其器(C、C++、Java、Python)

热门文章

  1. 实习每日总结_20161222
  2. 手把手教你写专利申请书/如何申请专利
  3. amigo幸运字符什么意思_QQ有什么魅力?为什么00后都喜欢?细节都在这些“标识”里...
  4. 合天网安实验室CTF-基础50-0x01
  5. JAVA+MySQL 图书馆借阅信息管理系统
  6. Spring Cloud Ribbon 全解 (1) - 总览篇
  7. HDU2571 命运(DP)
  8. Ardupilot移植经验分享(1)
  9. java zip解压 中文_java解压ZIP 解决中文乱码 (GBK和UTF-8)
  10. python爬虫之糗事百科