标签:方式 序号 print 多个 color ict 条件 应用 logs
一无所知的世界,走下去,才有惊喜。 Hello Python - day6!
[x for x in 内容] [x for x in 内容 if 条件] 1)把要生成的元素x放到前面,执行的时候,先执行后面的for循环 2)后面跟上for循环,可以有多个for循环,也可以在for循环后面再加个if条件 3)for循环后面可以是任何方式的迭代器(元组、列表、生成器等)只要迭代对象的元素中至少有一个值
1 >>> a = "abcd" 2 >>> [x for x in a] 3 [‘a‘, ‘b‘, ‘c‘, ‘d‘] 4 5 展开写为: 6 >>> a = "abcd" 7 >>> b = [] 8 >>> for x in a: 9 ... b.append(x) 10 ... 11 >>> print b 12 [‘a‘, ‘b‘, ‘c‘, ‘d‘]
1 >>> [m+n for m in ‘abc‘ for n in ‘ABC‘] 2 [‘aA‘, ‘aB‘, ‘aC‘, ‘bA‘, ‘bB‘, ‘bC‘, ‘cA‘, ‘cB‘, ‘cC‘] 3 4 展开写为: 5 >>> b = [] 6 >>> for n in ‘ABC‘: 7 ... for m in ‘abc‘: 8 ... b.append(n+m) 9 ... 10 >>> print b 11 [‘Aa‘, ‘Ab‘, ‘Ac‘, ‘Ba‘, ‘Bb‘, ‘Bc‘, ‘Ca‘, ‘Cb‘, ‘Cc‘]
1 >>> [x*x for x in range(1,11) if x%2 == 0] 2 [4, 16, 36, 64, 100] 3 4 展开写为: 5 >>> a = [] 6 >>> for x in range(1,11): 7 ... if x%2 == 0: 8 ... a.append(x*x) 9 ... 10 >>> print a 11 [4, 16, 36, 64, 100] 12 13 14 实际用例:迭代字典生成列表 15 >>> dict = {‘name‘:‘guanqing‘,‘age‘:‘28‘,‘sex‘:‘man‘} 16 >>> field = [k for k,v in dict.items()] 17 >>> value = [v for k,v in dict.items()] 18 >>> field 19 [‘age‘, ‘name‘, ‘sex‘] 20 >>> value 21 [‘28‘, ‘guanqing‘, ‘man‘]
1 dict = {k:v for (k,v) in iterable} #iterable 可迭代的,就是可以被for循环的 2 3 可以用任何方式的迭代器(元组、列表、生成器等)只要可迭代队形的元素中有两个值 4 5 >>> c = [4, 16, 36, 64, 100] 6 >>> {v:v for v in c} 7 {16: 16, 36: 36, 4: 4, 64: 64, 100: 100} 8 >>> {v:v*2 for v in c} 9 {16: 32, 36: 72, 4: 8, 64: 128, 100: 200} 10 >>> {v:v*2 for v in ‘abcd‘} 11 {‘a‘: ‘aa‘, ‘c‘: ‘cc‘, ‘b‘: ‘bb‘, ‘d‘: ‘dd‘} 12 >>> d = {‘a‘: ‘aa‘, ‘c‘: ‘cc‘, ‘b‘: ‘bb‘, ‘d‘: ‘dd‘} 13 >>> {v:k for k,v in d.items()} 14 {‘aa‘: ‘a‘, ‘cc‘: ‘c‘, ‘dd‘: ‘d‘, ‘bb‘: ‘b‘}
列表和字典生成式的区别:
列表生产式:前面只需要是用一个值,后面for循环可迭代对象,用[]括住整个语句
字典生产式:前面需要使用两个值,后面for循环存在2个值的可迭代队形,用{}括住整个语句
user = (1,‘wd‘,‘18‘,‘sa‘) # 数据库传来的数据 …… …… {‘age‘:‘18‘,‘id‘:‘1‘,‘name‘:‘wd‘,‘job‘:‘sa‘} # 转换完的样式 方式一: >>> user=(1,‘guanqing‘,‘28‘,‘sa‘) >>> field=[‘id‘,‘name‘,‘age‘,‘job‘] >>> zip(field,user) [(‘id‘, 1), (‘name‘, ‘guanqing‘), (‘age‘, ‘28‘), (‘job‘, ‘sa‘)] >>> dict(zip(field,user)) {‘job‘: ‘sa‘, ‘age‘: ‘28‘, ‘id‘: 1, ‘name‘: ‘guanqing‘} zip函数详解:http://www.jb51.net/article/53051.htm 方式二: >>> field =[‘id‘,‘name‘,‘age‘,‘job‘] >>> user=(1,‘guanqing‘,‘28‘,‘sa‘) >>> dict((k,user[i]) for i,k in enumerate(field)) {‘job‘: ‘sa‘, ‘age‘: ‘28‘, ‘id‘: 1, ‘name‘: ‘guanqing‘} 语句解析: 1)通过enumerate函数取出field列表中信息和对其对应的账号 >>> field =[‘id‘,‘name‘,‘age‘,‘job‘] >>> for i,k in enumerate(field): ... print i,k ... 0 id 1 name 2 age 3 job 2)通过序号可以获取到user列表中对应的信息 3)使用字典生产式,依托两个列表信息创建字典 >>> dict((k,user[i]) for i,k in enumerate(field)) {‘job‘: ‘sa‘, ‘age‘: ‘28‘, ‘id‘: 1, ‘name‘: ‘guanqing‘}
标签:方式 序号 print 多个 color ict 条件 应用 logs
原文地址:http://www.cnblogs.com/guanqingye/p/7509394.html