Python_列表解析【i for循环 if i】

Python_列表解析【i for循环 if i】要求 列出 1 10 中大于等于 4 的数字的平方 1 普通方法 gt gt gt L gt gt gt for i in range 1 11 if i gt 4 L

大家好,我是讯享网,很高兴认识大家。
要求:列出1~10中大于等于4的数字的平方 1、普通方法: >>> L = [] >>> for i in range(1,11): ... if i >= 4: ... L.append(i2) ... >>> print L [16, 25, 36, 49, 64, 81, 100] 2、列表解析 >>>L = [ i2 for i in range(1,11) if i >= 4 ] >>>print L [16, 25, 36, 49, 64, 81, 100] 

讯享网

if判断for循环中满足条件的i 进行 左边i操作

深入

讯享网要求:列出"/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'] 
要求:实现两个列表中的元素逐一配对。 1、普通方法: >>> L1 = ['x','y','z'] >>> L2 = [1,2,3] >>> L3 = [] >>> for a in L1: ... for b in L2: ... L3.append((a,b)) ... >>> print L3 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)] 2、列表解析: >>> L1 = ['x','y','z'] >>> L2 = [1,2,3] L3 = [ (a,b) for a in L1 for b in L2 ] >>> print L3 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)] 

列表解析比使用普通方法的速度几乎可以快1倍


讯享网

娱乐

讯享网print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)])) 

PS:本文原创首发于公众号「让我遇见相似的灵魂」,回复关键字获取数十本程序员经典电子书。

小讯
上一篇 2025-03-10 23:01
下一篇 2025-01-26 07:41

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/48283.html