一.安装Python
这个就不多说, 网上一大把,注意环境变量。在家学习,我就主要用windows的版本。
二 Python IDE
我使用的PyCharm
三. Python基础
3.1 注释采用#的方式
3.2 采用缩进的方式,表示逻辑,没有大括号。
3.3 数据类型
整数
浮点数(小数)例如1.23 很大的浮点数比如1.23x109就是1.23e9
字符串以单引号’或双引号"括起来的任意文本,注意转义,如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用’’’…’’'的格式表示多行内容。
bool值
空值 用None表示
变量 变量名必须是大小写英文、数字和_的组合,且不能用数字开头
常量 PI=3.14159265359
3.4格式化:
占位符 | 替换内容 |
---|---|
%d | 整数 |
%f | 浮点数 |
%s | 字符串 |
%x | 十六进制 |
format()
‘Hello, {0}, 成绩提升了 {1:.1f}%’.format(‘小明’, 17.125)
3.5 list和tuple
classmates = ['Michael', 'Bob', 'Tracy']
classmates = ('Michael', 'Bob', 'Tracy') #元祖
list和tuple(元祖)是Python内置的有序集合,一个可变,一个不可变。根据需要来选择使用它们。
3.6 循环和if-else
for x in …
sum=0;
for x in [1,2, 3, 4]:
sum+=x;
print(sum);
if-else
if-elif-else
3.7 dict 和set
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
dict的增删改不用多说
dict的遍历
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
for key, value in d.items():
print('key:' + key)
print('value: {0}'.format(value))
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
d=set([1,2,2,3])
d {1,2,3}
用户输入
input() 用户输入一些文本 输入内容为字符串
temp = input("请输入一些内容:")
print(int(temp))
3.8 函数
- 定义函数
def m_abs(x):
if x>10:
return x;
esle:
return 0;
3.9 切片
切片: 指定数组索引的位置 classmates[0:3]或者classmates[:3] 0-3索引的数据。classmate[2:] :索引2到最后一个数据。
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0:3]
['Michael', 'Sarah', 'Tracy']
3.10 map()和reduce()方法
接收一个函数和一个序列
map()的作用是什么?返回一个数组 函数的数组
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce()的作用是什么? 求函数的总和
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
def add(x, y):
return x + y
reduce(add, [1, 3, 5, 7, 9])
25
例子:字符串转浮点型 ‘123.456’—>123.456
def str2float(s):
DIGITS = {‘0’: 0, ‘1’: 1, ‘2’: 2, ‘3’: 3, ‘4’: 4, ‘5’: 5, ‘6’: 6, ‘7’: 7, ‘8’: 8, ‘9’: 9}
p=s.index(".")
s=s[:p]+s[p+1:] #去掉点的字符串
#map的方法是将字符串分为字符数组
#reduce求积
return reduce(lambda x, y: x*10+y, map(lambda x: DIGITS[x], s))/pow(10,len(s)-p)
filer()
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
sort()函数
3.11 lambda函数 匿名函数
lambda x: x * x实际上就是:
def f(x):
return x * x
3.12 OOP
3.13 File IO StringIO/BytesIO
1.读文件
with open('test.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
2.写文件
with open('test2.txt', 'w') as file_object:
context = input()
file_object.write(context)
‘w’:写
‘a’: append 附加
3.14 序列化
json.dump() //将json格式的数据写入到文件对象
import json
nums = [1, 2, 3, 4, 5]
with open('test3.json', 'w') as f_obj:
json.dump(nums, f_obj)
json.load() //从文件中加载到内存中,json格式
with open('test3.json') as f_obj:
context = json.load(f_obj)
print(context)
pickle.dump() 序列化,字典类型
import pickle
d = dict(name='Bob', age=20, score=88)
pickle.dumps(d)
f = open('dump.txt', 'wb')
pickle.dump(d, f)
f.close()
pickle.loads() 反序列化
f = open('dump.txt', 'rb')
d = pickle.load(f)
f.close()
d
{‘age’: 20, ‘score’: 88, ‘name’: ‘Bob’}
dict 序列化为 JSON对象
import json
d = dict(name='Bob', age=20, score=88)
json.dumps(d)
‘{“age”: 20, “score”: 88, “name”: “Bob”}’
JSON对象反序列化为dict python对象
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str))
JSON序列化 class对象
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
print(json.dumps(s))
报TypeError错误
最简单的办法
print(json.dumps(s, default=lambda obj: obj.__dict__))
反序列化Json对象
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
3.15 进程和线程
多线程
Python的标准库提供两个模块:_thread (低级模块)和 threading(高级模块)
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
def loop():
print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join() //结束
Lock------共享资源, 上锁
balance=0
lock = threading.Lock()
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(1000):
lock.acquire()
try:
change_it(n)
finally:
lock.release()
ThreadLocal 变量
ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题