Set (dữ liệu không có thứ tự với phép toán logic tối ưu)

Các kiểu dữ liệu trong Python

Jason Myers

Instructor

Set

  • Duy nhất
  • Không có thứ tự
  • Có thể thay đổi
  • Triển khai Lý thuyết Tập hợp trong Python
Các kiểu dữ liệu trong Python

Tạo set

  • Tạo set từ list
cookies_eaten_today = ['chocolate chip', 'peanut butter', 
   ...: 'chocolate chip', 'oatmeal cream', 'chocolate chip']

types_of_cookies_eaten = set(cookies_eaten_today)
print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter'])
Các kiểu dữ liệu trong Python

Sửa đổi set

  • .add() thêm một phần tử
types_of_cookies_eaten.add('biscotti')

types_of_cookies_eaten.add('chocolate chip')

print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter', 'biscotti'])
Các kiểu dữ liệu trong Python

Cập nhật set

  • .update() nhập thêm từ set hoặc list khác
cookies_hugo_ate = ['chocolate chip', 'anzac']

types_of_cookies_eaten.update(cookies_hugo_ate)

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream',  'peanut butter', 'biscotti'])
Các kiểu dữ liệu trong Python

Xóa dữ liệu khỏi set

  • .discard() xóa một phần tử theo giá trị, an toàn
  • .pop() xóa và trả về một phần tử bất kỳ (KeyError nếu rỗng)
types_of_cookies_eaten.discard('biscotti')

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
types_of_cookies_eaten.pop()
types_of_cookies_eaten.pop()
'chocolate chip'
'anzac'
Các kiểu dữ liệu trong Python

Phép toán trên set - tương đồng

  • Phương thức .union() trả về hợp của hai set (or)
  • .intersection() tìm phần giao (and)
cookies_jason_ate = set(['chocolate chip', 'oatmeal cream',
'peanut butter'])
cookies_hugo_ate = set(['chocolate chip', 'anzac'])

cookies_jason_ate.union(cookies_hugo_ate)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
cookies_jason_ate.intersection(cookies_hugo_ate)
set(['chocolate chip'])
Các kiểu dữ liệu trong Python

Phép toán trên set - khác biệt

  • .difference() trả về phần tử có trong set gọi phương thức nhưng không có trong đối số (-)
  • Lưu ý set mục tiêu!
cookies_jason_ate.difference(cookies_hugo_ate)
set(['oatmeal cream', 'peanut butter'])
cookies_hugo_ate.difference(cookies_jason_ate)
set(['anzac'])
Các kiểu dữ liệu trong Python

Hãy thực hành!

Các kiểu dữ liệu trong Python

Preparing Video For Download...