推导式

面向 R 用户的 Python

Daniel Chen

Instructor

推导式就是循环

  • 遍历列表
  • 执行某个函数
  • 将结果加入新列表
面向 R 用户的 Python

列表推导式

循环
data = [1, 2, 3, 4, 5]
new = []
for x in data:
    new.append(x**2)
print(new)
[1, 4, 9, 16, 25]
推导式
data = [1, 2, 3, 4, 5]

new = [x**2 for x in data]
print(new)
[1, 4, 9, 16, 25]
面向 R 用户的 Python

字典推导式

循环
data = [1, 2, 3, 4, 5]
new = {}

for x in data:
    new[x] = x**2
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
推导式
data = [1, 2, 3, 4, 5]

new = {x: x**2 for x in data}
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
面向 R 用户的 Python

`for` 循环的替代方案

  • 使用 for 循环迭代
  • R:sapplylapplyapply
  • Python:map 函数和 apply 方法
面向 R 用户的 Python

Map

For 循环
def sq(x):
    return x**2

l = [1, 2, 3]
for i in l:
    print(sq(i))
1
4
9
Map
map(sq, l)
<map at 0x7f41cca38358>
list(map(sq, l))
[1, 4, 9]
面向 R 用户的 Python

Passons à la pratique !

面向 R 用户的 Python

Preparing Video For Download...