Comprehensions

給 R 使用者的 Python

Daniel Chen

Instructor

Comprehensions 就是迴圈

  • 迭代(loop)串列
  • 執行函式
  • 將結果加入新串列
給 R 使用者的 Python

List comprehension

迴圈
data = [1, 2, 3, 4, 5]
new = []
for x in data:
    new.append(x**2)
print(new)
[1, 4, 9, 16, 25]
Comprehension
data = [1, 2, 3, 4, 5]

new = [x**2 for x in data]
print(new)
[1, 4, 9, 16, 25]
給 R 使用者的 Python

Dictionary comprehension

迴圈
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}
Comprehension
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

一起來練習吧!

給 R 使用者的 Python

Preparing Video For Download...