namedtuple

ประเภทข้อมูลใน Python

Jason Myers

Instructor

namedtuple คืออะไร?

  • tuple ที่แต่ละตำแหน่ง (คอลัมน์) มีชื่อกำกับ
  • รับประกันว่าแต่ละรายการมี property เหมือนกัน
  • ใช้แทนแถวใน pandas DataFrame ได้
ประเภทข้อมูลใน Python

สร้าง namedtuple

  • ส่งชื่อและรายการฟิลด์เข้าไป
from collections import namedtuple

Eatery = namedtuple('Eatery', ['name', 'location', 'park_id', ...: 'type_name'])
eateries = []
for eatery in nyc_eateries: details = Eatery(eatery['name'], eatery['location'], eatery['park_id'], eatery['type_name']) eateries.append(details)
ประเภทข้อมูลใน Python

แสดงผลลัพธ์ตัวแรก

print(eateries[0])
Eatery(name='Mapes Avenue Ballfields Mobile Food Truck',
location='Prospect Avenue, E. 181st Street',
park_id='X289', type_name='Mobile Food Truck')
ประเภทข้อมูลใน Python

การใช้งาน namedtuple

  • แต่ละฟิลด์เข้าถึงได้ผ่าน attribute ของ namedtuple
for eatery in eateries[:3]:
    print(eatery.name)
    print(eatery.park_id)
    print(eatery.location)
Mapes Avenue Ballfields Mobile Food Truck
X289
Prospect Avenue, E. 181st Street

Claremont Park Mobile Food Truck
X008
East 172 Street between Teller & Morris avenues ...
ประเภทข้อมูลใน Python

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

ประเภทข้อมูลใน Python

Preparing Video For Download...