文章字数:987,阅读全文大约需要3分钟
指定字符编码
# -*- coding: utf-8 -*-
输入输出
- 输入
name = input()
- 输出
print('1+1=',1+1)
循环
if
1
2
3
4
5
6
7
8# :后面的缩进(4个空格)都是代码块
a = 100
if a >= 0:
print(a)
elif a = 0:
print(0)
else:
print(-a)for
1 | names = [1,2,3,5] |
- while
1 | n = 0 |
- 退出
break
退出所有循环continue
退出本次循环
数据类型
变量不用声明,直接用 a=123
- 整数
1
- 浮点数
1.23
- 字符串
' '
" "
r' '
内部不转义''' sss '''
多行文本
- 布尔值
True
False
使用and
or
not
运算 - 空值
None
集合
list
- 声明
classmates = ['Michael', 'Bob', 'Tracy']
- 长度
len(classmates)
- 正向下标取值
classmates[0]
第一个 - 负向下标取值
classmates[-1]
最后一个 - 追加到末尾
classmates.append('Adam')
- 插入指定位置
classmates.insert(1, 'Jack')
- 删除末尾
classmates.pop()
- 删除指定位置
classmates.pop(1)
- 切片获取
r[0:3]
从0取到3,0可省略
tuple
不可变集合
- 声明
classmates = ('Michael', 'Bob', 'Tracy')
- 声明空的
tuple
:t = ()
- 声明一个:
t = (1,)
为了和数值型区分,后面加,
dict
:键值对
- 声明
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
- 取出
d['Michael']
或者d.get('Michael')
- 判断是否
key
在字典中'Thomas' in d
返回布尔 - 删除
d.pop('Bob')
set
无序集合
- 声明
s = set([1, 2, 3])
- 添加
s.add(4)
- 删除
remove(key)
- 交集并集
s1 & s2
s1 | s2
函数
函数赋值
a = abs
指向abs()
,然后a()
声明
1
2
3
4
5def my_fun(x):
if x >= 0:
return x
# 返回None
return空函数
1 | def nop(): |
- 返回多值
1 | def xx(): |
对象
- 对象迭代
1 | d = {'a': 1, 'b': 2, 'c': 3} |
- 声明
1 | # object代表父类 |
c = Cl('123')
指定对象可以使用的属性
__slots__ = ('name', 'age')
仅当前类有用,子类无作用toString 写
__str__
方法类作用于
len()
:写__len__
方法对象可以被遍历
1 | def __iter__(self): |
- get set
1 |
|
s.score
:等于s.get_sore()
s.score = 60
:s.set_sore(60)
函数式编程
- map/reduce
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
f是函数,接收一个值,map会把list的参数一个个传进去
reduce(f, [x1, x2, x3, x4])
f是函数,接收两个值第一个是上一个的返回值,第二个是list的元素
filter
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
返回满足条件的集合sorted([36, 5, -12, 9, -21])
排序函数可以返回函数
获取函数变量的方法名
fun.__name__
模块
- 定义
abc.py
就是abc
模块 - 引入
import abc
常用方法
range(5)
生成 0-5 的有序集合list(range(5))
展示listb = a.replace('a', 'A')
字符替换help(abs)
查看函数说明abs(100)
取整int()
转换类型max(1,2,3,)
取最大值hex()
十进制转16now()
现在的时间type('abc')
获取类型,也可以传对象
io
- 打开文件
f = open('/Users/michael/test.txt', 'r')
r只读f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
指定字符编码f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')
字符编码错误忽略
读取
f.read()
关闭
f.close()
安全打开(有异常也关闭)
1 | try: |
自动关闭
1
2with open('/path/to/file', 'r') as f:
print(f.read())其它读
read(size)
读取固定大小readline()
读取一行readlines()
读一行,返回所有内容的list
- 写
- 覆盖
w
追加a
f.write('Hello, world!')
- StringIO,BytesIO
f = StringIO('Hello!\nHi!\nGoodbye!')
string转成iof = BytesIO()
然后写f.write('中文'.encode('utf-8'))
f.getvalue()
:b'\xe4\xb8\xad\xe6\x96\x87'
二进制数据
- 文件目录
import os
os.rename('test.txt', 'test.py')
重命名os.remove('test.py')
删除os.mkdir('/Users/michael/testdir')
创建目录os.rmdir('/Users/michael/testdir')
删除目录
- 对象写入
- 转换成bytes:
1
2
3
4
5import pickle
f = open('dump.txt', 'wb')
d = dict(name='Bob', age=20, score=88)
pickle.dumps(d)
f.close() - 转json
1
2
3
4
5import json
d = dict(name='Bob', age=20, score=88)
json.dumps(d)
# 解析json
json.loads(json_str)
多线程
- 支持多进程
- 多线程
1
2
3
4
5
6def loop():
...
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()