循环 列表推导式 eval exec

断言

assert 0<age<100,"the age must belong (0,100)"

循环

在循环中增加else子句:它仅仅在没有调用break时执行

from math import sqrt
for n in range(99,81,-1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
else:
    print "Didn't find it"

zip()

for name,age in zip(names,ages):
print name, age

zip可以用于任意多的序列,可以处理不等长的序列,当最短的序列用完时为止.

enumerate()

产生用于迭代的(索引,值)对

for index,string in enumerate(strings):
    print index,string

列表推导式

得到名字首字母相同的男孩子和女孩子

girls=['alice','bernice','clarice']
boys=['chris','arnols','bob']
[b+'+'+g for b in boys for g in girls if b[0]==g[0]]

更加有效率的方式

girls=['alice','bernice','clarice']
boys=['chris','arnols','bob']
letterGirls = {}
for girl in girls:
letterGrils.setdefault(girl[0],[]).append(girl)

[b+'+'+g for b in boys for g in letterGirls[b[0]]]

eval:将字符串作为表达式计算

命名空间或作用域
for example:

scope = {}
scope['x'] = 2
scope['y'] = 3
eval('x * y',scope)


exec: 执行字符串

命名空间或作用域
for example:

scope = {}
exec 'x=2' in scope
eval('x*x'.scope)
posted @ 2017-06-17 22:39  jinzhongxiao  阅读(242)  评论(0编辑  收藏  举报