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
  • 相关阅读:
    ffmpeg基本用法
    MySQL中使用like查找汉字 Incorrect string value 解决办法
    mysql存储过程变量的拼接
    解决IIS8中 URLRewriter 不能使用的方法
    Unix系统介绍
    远程控制客户端界面介绍
    远程控制之登录界面设计
    搞了一周,终于把视频流在局域网内传输搞定
    servelet
    前后台贯穿
  • 原文地址:https://www.cnblogs.com/db2zos/p/4660007.html
Copyright © 2011-2022 走看看