list and dictionary comprehension

You can think of a list or dictionary comprehension as a one-line for loop that creates a new list or dictionary from another list. The pattern of
a list comprehension is as follows:

new_list = [expression for variable in old_list if expression]

new_dict = {expression:expression for variable in list if expression}

sample

x=[1,2,3,4]
x_squared=[item * item for item in x if item >2]

x_squared_dict={item:item*item for item in x}

posted on 2012-08-07 16:28  grep  阅读(209)  评论(0)    收藏  举报