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}
浙公网安备 33010602011771号