大家好,小编为大家解答高一编程代码期末作业的问题。很多人还不知道高一编程python题目,现在让我们一起来看看吧!
##Python笔记随笔 有时间完善
//数据类型//数字(number):float int bool complex
type(2/2)float
type(2//2)整除int
二进制
0b10->2
0b11->3
八进制
0o11
十六进制
0x11
bin(0x11);(各种)进制转换为2进制
int();转为10进制
hex();转为16进制
oct();转为8进制
bool布尔类型:真True(非零)/假False(0)(’’[]{})(None)
complex 复数 36j
组:序列(字符串str 列表list 元组 tuple)集合 set 字典dict
str 字符串 不可变性
表示方法:单引号 双引号 三引号
\转义字符
每行宽度79
(’’’ “”" 多行输入) \n换行 \t \r ’ \n r
+字符串拼接
*字符串多次输出
字符串中取单个字符
字符访问
“hello world”[0] 输出h
“hello world”[1] 输出e
“hello world”[-1] 输出d
“hello world”[-3] 输出r
“hello world”[0:4] 输出hell :后面需要到下一个字符
“hello world”[6:-1] 输出worl
“hello world”[6:] 输出world
步长 切片操作
1.列表list[1,2,3,4,5,6]
列表可多类型,多嵌套
[[],[],[],[],[]]
列表访问(同上)[0:3]
注:多组访问输出依旧是列表格式
2.元组(tuple)
(1,2,3,4,5)
其他暂时与列表相同
单一不构成组,加个逗号,
in / not in 判断
len 序列长度
max min 序列中最大小 字符acsii
ord 显示acsii码
集合set
1.无序的,没有索引,不能切片
{1,2,3,4,5}
2.不重复
3.求两个集合差集 -
4.求两个集合交集 &
5.并集 |
如何定义一个空集合
set()
字典 dict
由多个 key:value 集合
{key1:value1,key2:value2…}
{key1:value1,key2:value2…} [key1]
不能有重复键
1 与’1‘键值不同
key 不可变类型
value :str int float list set dict
空的字典{}
变量与运算符
A=[1,2,3]
B=[1,2]
A+B=[1,2,3,1,2]
变量名–字母数字下划线区分大小写
动态语言 没有类型限制
type 可以做变量值
int str tuple (不可变 )值类型 list set dict引用类型(指针)
id()查看地址
b=[1,2,3]
b.append(4)//在尾部追加
[1,2,3,4]
多维’数组‘
a=(1,2,3,[1,2,5])
a[3][2]=5
2**2 ->2的2次方
算术运算符
/ // %+ -* …
赋值运算符
= += *= /= %= **= //=
关系(比较)运算符(优先级大于赋值)
== != > < >= <=
集合 字符 都可以比较
逻辑运算符(返回布尔类型)或者返回真值
and(&&), or(||), not (非) not >and>优先级or
成员运算符
in 、not in在与不在
身份运算符(对象的三大特征)身份 类型 值
is ,is not(还需要考虑地址是否相同)
位运算符
& (按位与),|(按位或) ,^(按位异或),~(按位取反),<<,>>(左移右移)
isinstance(a,int)判断a是不是整型
isinstance(a,(int,float))判断a是不是其中一种
isinstance可以判断子类是不是
分支,循环,条件,枚举
if key:
print()
else:
print()
通过缩进判断句子属于哪一个分支
input()输入
pass 空语句 站位语句
elif
a=int(a)类型转换
循环
while else
for
for 主要是用来遍历、循环 序列 集合 字典
a = ['a','b','c']
for x in a:
print(x)
break continue
else属于循环体内
for x in range(0,10):
print(x,end='|')
0|1|2|3|4|5|6|7|8|9|
for x in range(10,0,-2):
print(x,end='|')
10|8|6|4|2|
a=[1,2,3,4,5,6,7,8]
b = a[0:len(a):2]
print(b)
[1, 3, 5, 7]
Python项目的组织结构
包(文件夹)(init.py)
模块(文件名)
类
函数,变量
命名空间 包.模块
import module_name (as) 导入模块
from module_name import a,b 导入部分变量、模块
from module_name import * 导入模块所有变量
all=[‘a’,‘b’] 模块内置属性,只能被导入此部分变量
\代码换行 ()代码换行
init.py 初始作用,导入库初始化
包和模块是不会重复导入的
避免循环引入
#函数
a=1.2341
a=round(a,2)#保留小数点2位
print(a)
1.23
def 关键字定义函数
def funcname(parameter_list)
pass
1.参数列表可以没有
2.return value 返回value、没有return 返回None
#import sys
#sys.setrecursionlimit(10000)设置最大递归
return 可以返回多个值
#序列解包
a,b,c=1,2,3
d=1,2,3
a,b,c=d
参数
关键字参数,可不考虑参数顺序
#面向对象
class Student():
# 类变量
sum =0
name = ''
age =0
def __init__(self,name,age ):
#构造函数 只能返回 None
#实例变量
self.name = name
self.age = age
def print_file(self):
print('name:'+ self.name)
print('age:'+str(self.age))
@classmethod #类方法 对象可以调用类方法
def plus_sum(cls):
cls.sum +=1
print(cls.sum)
@staticmethod #静态方法 对象和类都可以访问
def add(x,y):
print()
dict
self.class
默认公开
__方法变量私有 在方法变量前加双下划线变私有
_类名__私有变量 可以在外访问私有变量
可以给对象动态添加公开变量
继承性
避免重复方法,变量
super(类名,self).init(name,age)调用父类函数super关键字
正则表达式—爬虫基础
JSON(XML)数据结构
正则表达式是一个特殊的字符序列,一个字符串是否与我们所设定的这样子的字符序列,相匹配。
快速检索文本,实现一些替换文本的操作
1.检查一串数字是否是电话号码
2、检测一个字符串是否符合email
3、把一个文本里指定的单词替换为另一个单词
a = ‘字符串’
print(a.index(‘字’)>-1)
print(‘串’,a)
字符集 单一字符
import re #re模块有很多方法供我们操作字符串
a = ‘字符串’
re.findall(‘字’,a) #返回[‘字’]
re.findall(‘正则表达式’,a)
a = ‘1h3j4l3byu2’
r=re.findall(’\d’,a) #’\d’元字符,数字字符
[a-z]
[^a-z]
\b
\B
\cx
\d [0-9]
\D [^0-9]
\f \x0c \cL
\n \x0d \cM
\s [\f\n\r\t\v ]空白字符
\S 非空白字符
\t
\v
\w []
\W
. 匹配所有字符除了换行符\n
贪婪非贪婪?
r=re.findall(‘a[]c’,a) #[]
数量词
r=re.findall(’[a-z]{3,6}’,a)#贪婪,匹配符合条件的3-6个字符的词组
r=re.findall(’[a-z]{3,6}?’,a)#非贪婪 ,
- 匹配0次或者无限多次
-
匹配一次或者无限多次
? 匹配0次或者一次import re
a=‘pytho8python1pythonn’
r=re.findall(‘python*’,a)
r1=re.findall(‘python+’,a)
r2=re.findall(‘python?’,a)
print(r,r1,r2)
([‘pytho’, ‘python’, ‘pythonn’], [‘python’, ‘pythonn’], [‘pytho’, ‘python’, ‘python’])
边界匹配
import re
qq = '10962000'
r = re.findall('\d{4,8}',qq) #四到八位的数字
r = re.findall('^\d{4,8}$',qq) #从字符串^开头匹配到结尾$
^开头 $末尾
import re
a='pythonpythonpython'
r=re.findall('(python){2}',a)
[‘python’]
[abc]abc或关系 (a,b,c)abc且关系
r=re.findall(‘P’,a,re.I) #re.I|re.S 忽略大小写|匹配所有字符包括换行符\n
def sub(pattern,repl,string,count=0,flags=0)
r=re.sub
参数一,正则表达式
参数二,要被替换成的字符串或要’对象执行的函数’!
参数三,原始字符串
参数四,所要替换的最大次数,默认0表示无限制替换下去
参数五,
a=a.replace('','') #参数一,正则表达式,参数二,改为
def convert(value):
matched = value.group() #具体内容
return '!!'+matched + '!!'
r=re.sub('',convert,a)
-------
import re
re.match('\d',a) 从首字母开始匹配,第一个不对则返回none
re.search('\d',a) 搜索着匹配
匹配成功一次则返回
span()
group()
import re
s='life is short,i use python''
None
r = re.searsh('(life.*python)',s)
print(r.group())
如何获取标签中间的内容
r = re.searsh('life(.*)python',s)
print(r.group(1)) #0,获取正则表达式完整内容;>1:访问内部()分组
而r = re.findall('life(.*)python',s)
print(r)直接就可以啦
priint(r.groups())也阔以
[‘is short,i use’]
json JavaScript Object Notation JavaScript对象表示
是一种轻量级的数据交换格式
数据格式
易于阅读
易于解析
网络传输效率高
跨语言交换数据
import json
json在Python中是字符串
json_str = '{"name":"cw","age":18}'
student = json.loads(json_str)
print(student)
{'name':'cw','age':18} #根据json格式转换,这里转成了字典dict格式,
#反序列化 与序列化
json Python
object dict
array list
string str
number int
number float
ture Ture
false False
null None
序列化
import json
json_str = json.dumps(student)
JSON 对象、JSON、JSON字符串
REST 服务的标准格式
枚举
from enum import Enum
class vip(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
print(vip.YELLOW)
print(vip.YELLOW.value)
#不可变,标签不 相同
可以有别名
字典
{‘yellow’:1,‘green’:2}
#可变
#会有相同标签
for v in vip.members.items():
print(v)
枚举转换
a=1
print(vip.a)
from enum import Enum
from enum import IntEnum,unique
@unique #’装饰器‘此时各类型值不能相同
class vip(IntEnum):
YELLOW = 1
GREEN = 'str' #XXXintenum 只能int类型
BLACK = 1 #Xxx unique 类性值不能相同
RED = 4
class vip(Enum):
YELLOW = 1
GREEN = 'str'
BLACK = 3
RED = 4
#函数式编程
#闭包=函数+环境变量#内部函数引用内部变量
一切皆对象
可在函数内部定义函数,作用域在函数内部
def curve_pre():
a=25
def curve(x):
return a*x*x*x
return curve
f=curve_pre()
print(f(2))
100
print(f.__closure__)
print(f.__closure__[0].cell_contents)
#得到函数内部a的值
global 可在函数内部定义全局变量
origin=0
def factory(pos):
def go(step):
nonlocal pos #定义非局部变量
new_pos = pos +step
pos = new_pos
return new_pos
return go
tourist = factory(origin)
print(tourist(2))
print(tourist(3))
print(tourist(5))
2
5
10
#匿名函数
def add(x,y):
return x+y
lambda parameter_list(参数列表):expression(表达式)
lambda x,y:x+y
如何调用匿名函数
f=lambda x,y:x+y
print(f(1,2))
#三元表达式
r= x if x>y else y
map-- class map(func,*iterables) #*表示可变参数,参数个数可不唯一
func :函数
*iterables :序列或集合
list_x =[1,2,3,4,5,6]
r= map(lambda x:x*x,list_x)
print(list(r))
[1,4,9,16,25,36]
def reduce(function,sequence,initial=None)#initial 初始值
#连续计算,连续调用lamabda
from functools import reduce
list_x =[1,2,3,4,5,6,7,8]
r = reduce(lambda x,y:x+y,list_x) #叠加
print(r)
36
map/reduce 大数据中编程模型
映射/归约 并行计算
函数式编程
#filter 过滤函数
list_x =[1,0,1,0,0,1]
r= filter(lambda x: Ture if x==1 else False,list_x)
print(list®)
命令式编程
装饰器(AOP设计模式?)
import time
print(time.time())#以时间戳的形式打印出当前时间
def decorator(func);
def wrapper(*args,**kw):
print(time.time())
func(*args,**kw) #**kw关键字参数
return wrapper
def f1():
print('123')
@decorator #可以直接调用原函数名就可以实现新功能
f1()
#f=decorator(f1)
#f()
#小爬虫# F12
明确目的
找到数据对应网页
分析网页的结构找到数据所在的标签位置
模拟HTTP请求,向服务器发送这个请求,获取到服务器返回给我们的HTML
用正则表达式提取我们要的数据
from urllib import request
class Spider():
url = 'https://live.bilibili.com/p/eden/area-tags'
root_pattern = '([\s\S]*?)'
def __fetch_content(self):
#这个方法可以接收一个URL 抓取一个网页地址
r = request.urlopen(Spider.url)
htmls = r.read()
htmls = str(htmls,encoding='utf-8')
return htmls
def __analysis(self,htmls):
root_html = re.findall(Spider.root_pattern,htmls)
a=1
def go(self):
htmls = self.__fetch_content()
self.__analysis(self, htmls)
spider = Spider()
spider.go()
beautifulsoup
scrapy
代理ip池
用字典代替switch
day = 6
def get_sunday():
return 'sunday'
switcher = {
0:get_sunday(),
1:'monday',
2:'tuesday'
}
day_name = switcher.get(day,'unkown')()
print(day_name)
#列表推导式
a=[1,2,3,4,5,6,7,8]
b=[i**2 for i in a if i>=5]
print(b)