数字
python表达式操作符
操作符 描述
yield 生成器函数发送协议
lambda args: expression 生成匿名函数名
x if y else z 三元选择表达式
x or y 逻辑或,x为假执行y
x and y 逻辑与
not x 逻辑非
x in y, x not in y 成员关系(可迭代对象集合)
x is y, x is not y 对象比较
x < y, x <= y, x > y, x >= y, x == y, x != y 大小比较
| 位或
^ 位异或
& 位与
x << y, x >> y 左右移位y位
+, -, *, / 加减乘除
// 小数除法
% 求模
~
** 幂运算
x[i] 索引
x[s:j:k] 分片
x( ... ) 调用(函数,方法,类等)
x.attr 属性引用
( ... ) 元祖,表达式,生成器表达式
[ ... ] 列表,列表解析
{ ... } 字典,set,set和字典解析
多个数计算使用小括号
(x + y) * z使用函数将十进制转八进制,十六进制,二进制
>>> oct(255)
'0377'
>>> hex(255)
'0xff'
>>> bin(255)
'0b11111111'
- 将八进制,十六进制,二进制转10进制数
>>> int('377',8)
255
>>> int('ff',16)
255
>>> int('11111111',2)
255
- 几个内置函数
>>> abs(-1)
1
>>> min(4,3,1,2)
1
>>> max(4,3,1,2)
4
>>> sum((1,2))
3
- random模块
>>> import random
>>> random.random() # 产生0-1的随机数
0.30664199990073959
>>> random.random()
0.068441346426145189
>>>
>>> random.randint(1,6)
6
>>> random.randint(1,6)
5
>>> random.randint(1,6)
5
>>> random.randint(1,6)
5
>>> random.randint(1,6)
2
>>> random.randint(1,6)
6
>>> random.choice(['Fengq','Xiongw','Maos','Wutq','Gaoc'])
'Fengq'
>>> random.choice(['Fengq','Xiongw','Maos','Wutq','Gaoc'])
'Maos'
>>> random.choice(['Fengq','Xiongw','Maos','Wutq','Gaoc'])
'Gaoc'
>>> random.choice(['Fengq','Xiongw','Maos','Wutq','Gaoc'])
'Wutq'
>>> random.choice(['Fengq','Xiongw','Maos','Wutq','Gaoc'])
'Wutq'
- 小数数字
>>> print(0.1+0.1+0.1 - 0.3) # 浮点数缺乏精确性
5.55111512313e-17
#使用小数对象改正结果。通过decimal模块的Decimal构造函数创建一个小数对象。
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
Decimal('0.3')
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal('0.0')
#decimal其他工具设置小数数值精度
>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1429')
>>> 19 + 1.33
20.329999999999998
>>> decimal.Decimal(str(19 + 1.33))
Decimal('20.33')
集合
- set支持表达式操作符运算
>>> y = set('bdxyz')
>>> x = set('abcdef')
>>> x
set(['a', 'c', 'b', 'e', 'd', 'f'])
>>>
>>> 'e' in x
True
>>> 'e' in y
False
>>> x - y
set(['a', 'c', 'e', 'f'])
>>> x | y
set(['a', 'c', 'b', 'e', 'd', 'f', 'y', 'x', 'z'])
>>> x & y
set(['b', 'd'])
>>> x ^ y
set(['a', 'c', 'e', 'f', 'y', 'x', 'z'])
>>> x > y, x < y
(False, False)
- 集合有特定方法
>>> z = x.intersection(y) #就像x & y
>>> z
set(['b', 'd'])
>>> z.add('SPAM')
>>> z
set(['b', 'd', 'SPAM'])
>>> z.update(set(['X','Y']))
>>> z
set(['Y', 'X', 'b', 'd', 'SPAM'])
>>> z.remove('b')
>>> z
set(['Y', 'X', 'd', 'SPAM'])
- 集合是可迭代对象
>>> for i in set('abc'):
... print(i)
...
a
c
b
习题
截断小数部分
int(n)
math.trunc(n)整数转小数
floot(n)