文章字数:987,阅读全文大约需要3分钟
指定字符编码 # -*- coding: utf-8 -*-
输入输出
- 输入
name = input()
- 输出
print('1+1=',1+1)
循环
if
1 2 3 4 5 6 7 8
| a = 100 if a >= 0: print(a) elif a = 0: print(0) else: print(-a)
|
for
1 2 3 4 5 6
| names = [1,2,3,5] for name in names print(name)
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x
|
- while
1 2 3 4
| n = 0 while n > 0: sum = sum + n n = n - 2
|
- 退出
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 5
| def my_fun(x): if x >= 0: return x return
|
空函数
- 返回多值
1 2 3 4 5
| def xx(): return 1,2
x, y = xx()
|
对象
1 2 3
| d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key)
|
1 2 3 4 5
| class Cl(object): def __init__(self, name) self.name = nema
|
c = Cl('123')
1 2 3 4 5
| def __iter__(self): return self def __next__(self):
|
1 2 3 4 5 6
| @property def score(self): return self._score
@score.setter def score(self, value):
|
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))
展示list
b = a.replace('a', 'A')
字符替换
help(abs)
查看函数说明
abs(100)
取整
int()
转换类型
max(1,2,3,)
取最大值
hex()
十进制转16
now()
现在的时间
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 2 3 4 5
| try: f = open('/Users/michael/test.txt', 'r') finally: if f: f.close()
|
自动关闭
1 2
| with 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转成io
f = 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 5
| import pickle f = open('dump.txt', 'wb') d = dict(name='Bob', age=20, score=88) pickle.dumps(d) f.close()
|
- 转json
1 2 3 4 5
| import json d = dict(name='Bob', age=20, score=88) json.dumps(d)
json.loads(json_str)
|
多线程
- 支持多进程
- 多线程
1 2 3 4 5 6
| def loop(): ...
t = threading.Thread(target=loop, name='LoopThread') t.start() t.join()
|