#用简介的方式去遍历可迭代对象生成需要格式的列表
int_list = [1,2,3,4,5]

qu_list = [item * item for item in int_list]
print (type(qu_list))
int_list = [1,2,-3,4,5]

qu_list = [item if item > 0 else abs(item) for item in int_list]

#笛卡尔积
int_list1 = [1,2]
int_list2 = [3,4]

qu_list = [(first, second) for first in int_list1 for second in int_list2]

my_dict = {
"key1":"bobby1",
"key2":"bobby2"
}

# qu_list = [(key, value) for key, value in my_dict.items()]
#
# qu_list2 = list(((key, value) for key, value in my_dict.items()))
#
# for item in qu_list2:
# print (item)

int_list = [1,2,3,4,5]

def process_item(item):
return str(item)

int_dict = {process_item(item):item for item in int_list}
#列表生成式,第一:能用尽量用, 因为效率高
print (int_dict)


1.列表推导式书写形式:  

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

#!/usr/bin/python
# -*- coding: utf-8 -*-

li = [1,2,3,4,5,6,7,8,9]
print [x**2 for x in li]

print [x**2 for x in li if x>5]

print dict([(x,x*10) for x in li])


print [ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8 ]

vec=[2,4,6]
vec2=[4,3,-9]
sq = [vec[i]+vec2[i] for i in range(len(vec))]
print sq

print [x*y for x in [1,2,3] for y in [1,2,3]]

testList = [1,2,3,4]
def mul2(x):
return x*2
print [mul2(i) for i in testList]

结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81]

[36, 49, 64, 81]

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}

[(5, 9), (7, 9), (9, 9)]

[6, 7, -3]

[1, 2, 3, 2, 4, 6, 3, 6, 9]

[2, 4, 6, 8]

3.总结:

  我觉得就是通过for 语句处理表达式里面的变量,如果还要加条件,就加if条件就可以了。