首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python_列表解析【i for循环 if i】

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

作者头像
瑞新
发布2020-07-08 11:20:29
6910
发布2020-07-08 11:20:29
举报
要求:列出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]

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)]))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档