• Python 列表推导


    1、列表推导表达式

    [表达式 for 变量 in 列表]
    [表达式 for 变量 in 列表 if 条件表达式]

    2、列表推导简单例子

      1) 简单推导

    # lc means list_comprehensions
    lc = [i for i in range(10)]
    print 'result: %s' % lc
    
    lc_add = [i + i for i in range(10)]
    print 'result: %s' % lc_add
    
    lc_square = [i**2 for i in range(10)]
    print 'result: %s' % lc_square
    
    lc_dict = dict([(i, i * 10) for i in range(10)])
    print 'result: %s' % lc_dict

      结果:

    result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    result: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    result: {0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}

      2) 带条件的推导

    lc_even = [i for i in range(10) if i % 2 == 0]
    print 'result: %s' % lc_even
    
    lc_odd = [i for i in range(10) if i % 2 == 1]
    print 'result: %s' % lc_odd
    
    lc = [x*y for x in range(0, 10, 3) for y in range(0, 10, 3)]
    print 'result: %s' % lc

      结果:

    result: [0, 2, 4, 6, 8]
    result: [1, 3, 5, 7, 9]
    result: [0, 0, 0, 0, 0, 9, 18, 27, 0, 18, 36, 54, 0, 27, 54, 81]

    3、简单优雅

    Python风格的语法是一种对小代码模式最有效的语法

  • 相关阅读:
    hihocoder 1049 后序遍历
    hihocoder 1310 岛屿
    Leetcode 63. Unique Paths II
    Leetcode 62. Unique Paths
    Leetcode 70. Climbing Stairs
    poj 3544 Journey with Pigs
    Leetcode 338. Counting Bits
    Leetcode 136. Single Number
    Leetcode 342. Power of Four
    Leetcode 299. Bulls and Cows
  • 原文地址:https://www.cnblogs.com/starrysky77/p/9309977.html
Copyright © 2020-2023  润新知