Python小技巧

摘自于网上的Python小技巧

Posted by 任天恒 on July 9, 2015
  1. 交换变量

    x=6
    y=5
    x,y=y,x
    print x,y
    >>>5,6
    
  2. 计算技巧

     # 2的5次方
     print 2**5
     >>>32
    
  3. 两个列表同时迭代

     nfc = ["Packers", "49ers"]
     afc = ["Ravens", "Patriots"]
     for teama, teamb in zip(nfc, afc):
     print teama + " vs. " + teamb
     >>> Packers vs. Ravens
     >>> 49ers vs. Patriots
    
  4. 带索引的列表迭代

     teams = ["Packers", "49ers", "Ravens", "Patriots"]
     for index, team in enumerate(teams):
     print index, team
     >>> 0 Packers
     >>> 1 49ers
     >>> 2 Ravens
     >>> 3 Patriots
    
  5. 列表推导

    已知一个列表,刷选出偶数列表方法:

     numbers = [1,2,3,4,5,6]
     even = []
     for number in numbers:
       if number%2 == 0:
         even.append(number)
    

    用下面方法写:

     numbers = [1,2,3,4,5,6]
     even = [number for number in numbers if number%2 == 0]  
    
  6. 将列表转换成字符串

     teams = ["Packers", "49ers", "Ravens", "Patriots"]
     print ", ".join(teams)
     >>> 'Packers, 49ers, Ravens, Patriots'
    
  7. 获取子列表

    x = [1,2,3,4,5,6]
    #前3个
    print x[:3]
    >>> [1,2,3]
    #中间4个
    print x[1:5]
    >>> [2,3,4,5]
    #最后3个(方法1)
    print x[-3:]
    >>> [4,5,6]
    #最后3个(方法2)
    print x[3:7]
    >>> [4,5,6]
    #奇数项
    print x[::2]
    >>> [1,3,5]
    #偶数项
    print x[1::2]
    >>> [2,4,6]
    
  8. 集合

    用到Counter库

    from collections import Counter
    print Counter("hello")
    >>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
    
  9. 迭代工具

    和collections库一样,还有一个库叫itertools

    from itertools import combinations
    teams = ["Packers", "49ers", "Ravens", "Patriots"]
    for game in combinations(teams, 2):
    print game
    >>> ('Packers', '49ers')
    >>> ('Packers', 'Ravens')
    >>> ('Packers', 'Patriots')
    >>> ('49ers', 'Ravens')
    >>> ('49ers', 'Patriots')
    >>> ('Ravens', 'Patriots')
    
  10. 负数索引切割列表

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[-4:-2]
    [7, 8]