三目运算符:
如果条件(紧跟在if后面)为真,表达式的结果为提供的第一个值(这里为friend),否则为第二个值,这里为stanger。
name = ‘gf’
status = ‘friends’ if name.endswith(‘gf’) else ‘stranger’
status
‘friends’
Python的比较运算符
表达式 描述
x==y x等于y(比较对象内容)
x<y x小于y
x>y x大于y
x>=y x大于等于y
x<=y x小于等于y
x!=y x不等于y
x is y x和y是同一对象(比较对象本身是否是同一对象)
x is no y x和y不是同一对象
x in y x是容器(或序列)y的成员
x is not in y x不是容器(或序列)y的成员
python也支持链式比较,如:0 < age < 100
ord可以获取函数的顺序值,chr是根据顺序值获取字符
bool运算符:and or not,可以随意组合
断言:assert(condition) <==>
if not condition:
crash Program
可以在断言后面加字符串,对断言做出说明:
age = -1
assert 0 < age < 100, ‘The age must be realistic’
Traceback (most recent call last):
File “”, line 1, in
AssertionError: The age must be realistic
通过设置步长跳过一些数,或者向下迭代,比如:
from math import sqrt
for i in range(99, 0, -1):
… root = sqrt(i)
… if root == int(root):
… print(i)
… break
…
81
list(range(0, 10, 2))
[0, 2, 4, 6, 8]
列表推导:是一种从其他列表创建列表的方式,类似于数学中的集合推导。
例子:
[x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]
[(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
[b+‘+’+g for b in boys for g in girls if b[0] == g[0]]
[‘Chris+Clarice’, ‘Arnold+Alice’, ‘Bob+Bernice’]
使用圆括号代替方括号并不能实现元组推导,而是创建生成器。
字典推导:使用花括号来执行,for前面有两个用冒号隔开的表达式,这两个表达式分别代表字典的键和值。
例子:
square = {i:‘{} squared is {}’.format(i, i**2) for i in range(10)}
square[8]
‘8 squared is 64’
pass、del、exec
Python中代码块不能为空,可以在不需要写代码的块中添加pass语句。
例子:
if name == ‘Ralph Auldus Melish’:
… print(‘Welcome’)
… elif name == ‘Enid’:
… pass
… elif name == ‘Bill Gates’:
… print(‘Access Denied’)
对于不再使用的对象,Python可以调用delete将其删除,这不仅会删除对象的引用,还会删除名称本身。
例子:
x = 1
del x
x
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘x’ is not defined
以下x和y指向同一列表,但是删除x的对象并没有删除y的对象,因为del该函数删除的只是名称x,而不是删除列表本身。Python没法直接删除值,对于不再使用的值,Python解释器会立即将它删除,为Python的回收器。
x = [‘Hello’, ‘World’]
y = x
y[1] = ‘Python’
del x
y
[‘Hello’, ‘Python’]
exec:将字符串作为代码执行。
例子:
exec(“print(‘Hello, World!’)”)
Hello, World!
在调用exec时,绝大多数情况下需要传给它一个命名空间,用于放置变量的地方,否则代码将污染自己当前的命名空间,例如:
from math import sqrt
exec(“sqrt = 1”)
sqrt(4)
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘int’ object is not callable
exec主要用于动态地创建代码字符串,如果这种字符串来自于其他地方(可能是用户),就无法确定它包含什么内容,因此,可以提供一个字典以充当命名空间。第二个参数:字典,用作代码字符串的命名空间。
例子:
from math import sqrt
scope = {}
exec(“sqrt = 1”, scope)
sqrt(4)
2.0
scope[‘sqrt’]
1
eval:计算用字符串表示的Python表达式的值,并返回计算结果。
例子:
eval(input('Enter an arithmetic expression: '))
Enter an arithmetic expression: >? 1+1
2
也可以向eval提供一个命名空间,可在使用这个命名空间前在其中添加一些值。同样一个命名空间可用于对此调用exec或eval。
例子:
scope = {}
scope[‘x’] = 2
scope[‘y’] = 3
eval(‘x*y’, scope)
6
scope = {}
exec(‘x = 1’, scope)
eval(‘x+1’, scope)
2

被折叠的 条评论
为什么被折叠?



