标签:div lis 迭代 运算 __next__ range 迭代器 内存 anaconda
if x > f: print(x) else: print(y)
x if x > y else y # 三元表达式
result=值1 if x<y else 值2
#方法一 L = [] for x in range(1, 11): L.append(x * x) #结果L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # 方法二:列表解析 [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
还可以使用两层循环,可以生成全排列:
[m+n for m in ‘ABC‘ for n in ‘XYZ‘] [‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]
d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } for k, v in d.items(): print(k, ‘=‘, v) y = B x = A z = C
:
d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } [k + ‘=‘ + v for k, v in d.items()] [‘y=B‘, ‘x=A‘, ‘z=C‘]
#遍历
s=‘hello‘ l=[] for i in s: res=i.upper() l.append(res) print(l)
#####################################
#列表解析:
s=‘hello‘
res=[i.upper() for i in s]
print(res)
要求:列出1~10所有数字的平方 #################################################### 1、普通方法: >>> L = [] >>> for i in range(1,11): ... L.append(i**2) ... >>> print L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] #################################################### 2、列表解析 >>>L = [ i**2 for i in range(1,11)] >>>print L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
要求:列出1~10中大于等于4的数字的平方 #################################################### 1、普通方法: >>> L = [] >>> for i in range(1,11): ... if i >= 4: ... L.append(i**2) ... >>> print L [16, 25, 36, 49, 64, 81, 100] #################################################### 2、列表解析 >>>L = [ i**2 for i in range(1,11) if i >= 4 ] >>>print L [16, 25, 36, 49, 64, 81, 100]
要求:列出"/var/log"中所有已‘.log‘结尾的文件 ################################################## 1、普通方法 >>>import os >>>file = [] >>> for file in os.listdir(‘/var/log‘): ... if file.endswith(‘.log‘): ... file.append(file) ... >>> print file [‘anaconda.ifcfg.log‘, ‘Xorg.0.log‘, ‘anaconda.storage.log‘, ‘Xorg.9.log‘, ‘yum.log‘, ‘anaconda.log‘, ‘dracut.log‘, ‘pm-powersave.log‘, ‘anaconda.yum.log‘, ‘wpa_supplicant.log‘, ‘boot.log‘, ‘spice-vdagent.log‘, ‘anaconda.program.log‘] ################################################## 2.列表解析 >>> import os >>> file = [ file for file in os.listdir(‘/var/log‘) if file.endswith(‘.log‘) ] >>> print file [‘anaconda.ifcfg.log‘, ‘Xorg.0.log‘, ‘anaconda.storage.log‘, ‘Xorg.9.log‘, ‘yum.log‘, ‘anaconda.log‘, ‘dracut.log‘, ‘pm-powersave.log‘, ‘anaconda.yum.log‘, ‘wpa_supplicant.log‘, ‘boot.log‘, ‘spice-vdagent.log‘, ‘anaconda.program.log‘]
egg_list=[‘鸡蛋%s‘ %i for i in range(10)] #列表解析 ############################################# laomuji=(‘鸡蛋%s‘ %i for i in range(10))#生成器表达式 print(laomuji) print(next(laomuji)) #next本质就是调用__next__ print(laomuji.__next__()) print(next(laomuji))
标签:div lis 迭代 运算 __next__ range 迭代器 内存 anaconda
原文地址:http://www.cnblogs.com/shenbuer/p/7375244.html