# Python列表推导式，集合推导式，元组推导式

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

# 列表推导
d = [i**2 for i in a]

#集合推导
e = {i**2 for i in a}

#元组推导
f = (i**2 for i in a)

print(type(d))

print(type(e))

print(type(f))
-------------------------

<class 'list'>
<class 'set'>
<class 'generator'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

a = [1, 2, 3, 4, 5, 6, 7, 8]
f = (i**2 for i in a)
for n in f:
print(n)
print(type(f))
---------------------------------------------

1
4
9
16
25
36
49
64
<class 'generator'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

a = [1, 2, 3, 4, 5, 6, 7, 8]
d = [i**2 for i in a if i >=5]
print(d)
---------------------

[25, 36, 49, 64]
1
2
3
4
5
6

a = [1, 2, 3, 4, 5, 6, 7, 8]
def conpute(x):
if(x >= 6):
return x**2
return x**3
f = [conpute(i) for i in a]
print(f)
----------------------------------------

[1, 8, 27, 64, 125, 36, 49, 64]
1
2
3
4
5
6
7
8
9
10

a = [1, 2, 3, 4, 5, 6, 7, 8]
def conpute(x):
if(x >= 6):
return x**2
return x**3
d = (conpute(i) for i in a)
x = []
for n in d:
x.append(n)
print(x)
---------------------------------------------------

[1, 8, 27, 64, 125, 36, 49, 64]
————————————————

01-10 5818

05-02 1666
02-07 198
03-26 790
04-01 155
10-20 39
03-19 1285
03-05 181
11-25 257
06-11 7041