您的位置:首页 > 编程语言 > Python开发

python-列表推倒式-轻量级循环

2016-03-06 00:51 621 查看
列表推倒式是利用其它列表创建新的列表的方法。

示例

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


当添加一个if语句到列表推倒式的时候

>>> [x*x for x in range(10) if x%2==0]
[0, 4, 16, 36, 64]


联合语句时候(男生女生首字母相同的在一起,好厉害O(∩_∩)O~~)

>>> boys=['amada','bwsf','cdws']
>>> girls=['alice','batterf','cauew']
>>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
['amada+alice', 'bwsf+batterf', 'cdws+cauew']


但是这个效率不是很高,他要把男生和女生的名字每个都要匹配一遍,so

boys=['amada','bwsf','cdws']
girls=['alice','batterf','cauew']
letterGirls={}
for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python-循环