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风格的语法是一种对小代码模式最有效的语法