zoukankan      html  css  js  c++  java
  • 如何写出优雅的Python

    Looping over a range of numbers

    Bad:

    for i in [0,1,2,3,4,5]:
        print i**2

    Good:

    for i in range(6):
        print i**2

    Looping over a collection:

    Bad:

    colors = [ 'red','green','blue','yellow']
    
    for i in range(len(colors)):
        print colors[i]

    Good:

    for i in colors:
        print colors[i]

    Looping backwards

    Bad:

    colors = ['red','green','blue','yellow']
    
    for i in range(len(colors)-1,-1,-1):
        print colors(i)

    Good:

    colors = ['red','green','blue','yellow']
    
    for color in reversed(colors):
        print color

    Looping over a collection and indicies

    Bad:

    colors = ['red','green','blue','yellow']
    
    for i in range(len(colors)):
        print i, '-->', colors[i]

     Good:

    colors = ['red','green','blue','yellow']
    
    for i,color in enmerate(colors):
        print i, '-->', colors[i]

    Looping over two collections

    Bad:

    names = ['raymond','rachel','mattew']
    colors = ['red','green','blue','yellow']
    
    n = min(len(names),len(colors))
    for i in range(n):
        print names[i],'-->',colors[i]

    Good:

    names = ['raymond','rachel','mattew']
    colors = ['red','green','blue','yellow']
    
    for name,color in zip(names,colors):
        print name,'-->',color

    Even beeter.(izip 依次处理,zip是全部读入后处理,如果在中间中断的话,izip不需要读入所有内容)

    from itertools import izip
    names = ['raymond','rachel','mattew']
    colors = ['red','green','blue','yellow']
    
    for name,color in izip(names,colors):
        print name,'-->',color
  • 相关阅读:
    1265 四点共面
    1298 圆与三角形
    1264 线段相交
    1185 威佐夫游戏 V2
    1183 编辑距离
    1089 最长回文子串
    HTML5 boilerplate 笔记(转)
    Grunt上手指南(转)
    RequireJS 2.0初探
    RequireJS学习笔记
  • 原文地址:https://www.cnblogs.com/db2zos/p/4660007.html
Copyright © 2011-2022 走看看