码迷,mamicode.com
首页 > 编程语言 > 详细

python 列表推导

时间:2016-02-01 09:34:05      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

python 列表推导

List Comprehensions
List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one.

最简单形式
[ expression-involving-loop-variable for loop-variable in sequence ]

if __name__ == "__main__":
    print [i for i in range(10)]

nested形式
[ expression-involving-loop-variables for outer-loop-variable in outer-sequence for inner-loop-variable in inner-sequence ]
与以下代码等价:

results = []
for outer_loop_variable in outer_sequence:
    for inner_loop_variable in inner_sequence:
        results.append( expression_involving_loop_variables )

filter形式
[ expression-involving-loop-variable for loop-variable in sequence if boolean-expression-involving-loop-variable
示例:

>> ListOfThreeMultiples = [x for x in range(10) if x % 3 == 0] 
# Multiples of 3 below 10
>> ListOfThreeMultiples
[0, 3, 6, 9]

python 列表推导

标签:

原文地址:http://www.cnblogs.com/AlexWei/p/5174297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!