Containers - lists และ dictionaries

Python สำหรับผู้ใช้ R

Daniel Chen

Instructor

Lists

  • คล้ายกับ vector และ list ใน R
  • เก็บข้อมูลหลายประเภทในที่เดียวกันได้ (เช่น [3, 2.718, True, 'hello'])
Python สำหรับผู้ใช้ R

การสร้าง list

R
l <- list(1, "2", TRUE)
l
[[1]]
[1] 1

[[2]]
[1] "2"

[[3]]
[1] TRUE
Python
l = [1, '2', True]
l
[1, '2', True]
Python สำหรับผู้ใช้ R

Python เริ่มนับ index จาก 0

Python เริ่มนับ index จาก 0

Python สำหรับผู้ใช้ R

การ subset list

R

ดึงสมาชิกตัวแรกจาก list ใน R

l[[1]]  # use 1
1
Python

ดึงสมาชิกตัวแรกจาก list ใน Python

l[0] # use 0
1
Python สำหรับผู้ใช้ R

Index ติดลบ

index ที่เป็นลบจะเริ่มนับจากท้าย

Python สำหรับผู้ใช้ R

Index ติดลบ

R
l <- list(1, "2", TRUE)
l[-1]
[[1]]
[1] "2"

[[2]]
[1] TRUE
Python
l = [1, "2", True]
l[-1]
True
Python สำหรับผู้ใช้ R

รวมขอบซ้าย ไม่รวมขอบขวา

รวมขอบซ้าย ไม่รวมขอบขวา

Python สำหรับผู้ใช้ R

คิดแบบเสาและช่องรั้ว

index 0           1           2           3           4           5
      |           |           |           |           |           |
      | element 0 | element 1 | element 2 | element 3 | element 4 |
      |           |           |           |           |           |
Python สำหรับผู้ใช้ R

การ slice ส่วนที่ 1

Python
l = [0, 1, 2, 3, 4]

l[0:3]
[0, 1, 2]
l[0:5:2]
[0, 2, 4]
Python สำหรับผู้ใช้ R

การ slice ส่วนที่ 2

แบบ Implicit
l[:3]
[0, 1, 2]
l[1:]
[1, 2, 3, 4]
l[::2]
[0, 2, 4]
แบบ Explicit
l[0:3]
[0, 1, 2]
l[1:5]
[1, 2, 3, 4]
l[0:5:2]
[0, 2, 4]
Python สำหรับผู้ใช้ R

Dictionaries

  • List ไม่มี label
  • Dictionary ใช้คู่ key:value
Python สำหรับผู้ใช้ R

Python: การสร้างและใช้งาน dictionary

d = {'int_value':3, 'bool_value':False, 'str_value':'hello'}

d
{'int_value': 3, 'bool_value': False, 'str_value': 'hello'}
d['str_value']
'hello'
Python สำหรับผู้ใช้ R

การหาความยาว

l = [0, 1, 2, 3, 4]
d = {'int_value':3, 'bool_value':False, 'str_value':'hello'}

len(l)
5
len(d)
3
Python สำหรับผู้ใช้ R

มาฝึกกันเถอะ!

Python สำหรับผู้ใช้ R

Preparing Video For Download...