判断循环语句语法说明:
1,if
if boolean_expression:
...
elif boolean_expression:
...
else
...
2,while
while boolean_expression:
while_suite
if boolean_expression2: continue
if boolean_expression3: break
else:
else_suite
3,for
for expression in object:
for_suite
if boolean_expression2: continue
if boolean_expression3: break
else:
else_suite
while True:
x = raw_input(‘Enter an entry: ‘)
if x == ‘q‘ or x == ‘quit‘:
break
else:
test.append(x)
列表解析和生成器表达式:
两者区别:
1,列表解析使用[],生成器使用()
2,列表解析一次性全部生产,如果数据量大,比较消耗资源,而生成器每次计算一个条目,把这个条目yield出来,效率高,内存消耗少。(和range,xrange类似)
列表解析
实例1:列出/var/log目录下所有.log后缀名的文件
s1=‘hello.log‘
s1.endswith(‘.log‘) #endswith()函数判断后缀名
True
import os #加载os模块,有很多
filelist1 = os.listdir(‘/var/log‘) #os.listdir() 函数列出目录下所有文件
help(str.endswith) #查看帮助
filelist2 = [i for i in filelist1 if i.endswith(‘.log‘)]
print filelist2
[‘boot.log‘, ‘pm-powersave.log‘, ‘anaconda.yum.log‘, ‘Xorg.0.log‘, ‘anaconda.ifcfg.log‘, ‘Xorg.9.log‘, ‘anaconda.storage.log‘, ‘dracut.log‘, ‘yum.log‘, ‘spice-vdagent.log‘, ‘wpa_supplicant.log‘, ‘anaconda.log‘, ‘anaconda.program.log‘]
实例2:实现l1,l2列表一次相向排序
l1 = [‘x‘,‘y‘,‘z‘]
l2 = [1,2,3]
l3 = [(i,j) for i in l1 for j in l2]
print l3
[(‘x‘, 1), (‘x‘, 2), (‘x‘, 3), (‘y‘, 1), (‘y‘, 2), (‘y‘, 3), (‘z‘, 1), (‘z‘, 2), (‘z‘, 3)]
生成器表达式
语法:
(expr for iter_var in iterable)
(expr for iter_var in iterable if cond_expr)
求幂运算
获取索引和值本身enumerate,此函数可以获取列别索引和值,可以生成字典
url = ‘www.baidu.com‘
In [84]: en
%env enumerate
In [84]: enumerate(url)
Out[84]: <enumerate at 0x1eb81e0>
In [85]: g1 = enumerate(url)
In [86]: g1.next()
Out[86]: (0, ‘w‘)
In [87]: g1.next()
Out[87]: (1, ‘w‘)
In [88]: g1.next()
Out[88]: (2, ‘w‘)
In [89]: g1.next()
Out[89]: (3, ‘.‘)