# python 列表推导以及推到练习

## 列表推导式：

[expr for value in collection ifcondition]

## 集合推导式：

{ expr for value in collection ifcondition }

1.names = [‘jane’,‘joe’,‘susan’,‘black’,‘leonaldo’]  ( for 循环遍历，与列表推导式 两种方法做)

list2 = []
names = ['jane','joe','susan','black','leonaldo']
lsit1 = [i for i in names if len(i)>4]
print(lsit1)

for i in lsit1:
if len(i) > 4:
list2.append(i)
print(list2)
['susan', 'black', 'leonaldo']
['susan', 'black', 'leonaldo']

2.使用列表推到式得出:0-30间能被3整除的数

list1 = [i for i in range(0,31) if i%3 == 0 ]
print(list1)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
3.

3.M,N矩阵对应元素的和元素的乘积    (提示：使用2for遍历)

m =[[1,2,3],
[4,5,6],
[7,8,9]]

n =[[2,2,2],
[3,3,3],
[4,4,4]]

list2 = []
m = [[1,2,3],
[4,5,6],
[7,8,9]]

n = [[2,2,2],
[3,3,3],
[4,4,4]]
list01 = [ m[i][j]*n[i][j] for i in range(0,3) for j in range(0,3)]

print(list01)
print(sum(list01))
for i in range(0,3):
for j in range(0, 3):
a = m[i][j] * n[i][j]
list2.append(a)
print(list2)
[2, 4, 6, 12, 15, 18, 28, 32, 36]
153
[2, 4, 6, 12, 15, 18, 28, 32, 36]

4.嵌套列表推到：

names=[['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'],['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]

names=[['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'],['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva'],'aaa']

name = [name1 for lst in names for name1 in lst if name1.count('e')>=2]
print(name)
['Jefferson', 'Wesley', 'Steven', 'Jennifer']

## 字典推导式：

{ key_expr: value_expr forvalue in collection if condition }

1. 使用item()方法颠倒键名和值

dict2 = {'a': 10, 'b': 34}
dict2 = {'a': 10, 'b': 34}
dict3 = {v:k for k,v in enumerate(dict2) }
print(dict3)
{'a': 0, 'b': 1}

2.  有四个数字：1、2、3、4，能组成多少个互不相同且无重复数字的三位数？各是多少？程序分析：可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列(用列表推导式)

list2 = [i*100+j*10+k for i in range(1,5) for j in range(1,5) for k in range(1,5) if i != k and i!= j and k !=j ]
print(list2)
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
3.. 列表分割

list = [0,0,0,1,1,2,3,3,3,2,3,3,0,0]
list0 = []
stat = 0
for i in range(1,len(list)):
if list[i - 1] != list[i]:
list0.append(list[stat:i])
stat = i
list0.append(list[stat:])
print(list0)


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120