Bài 04 - Collections Trong Python

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Bài 4 Collections trong Python

Bài 4 Collections trong Python 1


MỤC TIÊU
• Giới thiệu về Collections

• Lists

• Tuples

• Sets

• Dictionaries

Bài 4 Collections trong Python 2


Giới thiệu
• Collection là dạng dữ liệu kiểu tập hợp được chia làm 4 loại trong Python

List is a collection which is ordered Tuple is a collection which is


and changeable. Allows duplicate ordered and unchangeable. Allows
members. duplicate members.

Set is a collection which is Dictionary is a collection which is


unordered and unindexed. No unordered, changeable and
duplicate members. indexed. No duplicate members.

Bài 4 Collections trong Python 3


List
• Là một tập hợp có thứ tự và có thể thay đổi, dữ liệu được liệt kê trong cặp [ ]

# tạo 1 list # in từ phần tử 3 đến cuối


flowers = ["Lan", "Hồng", "Cúc","Ly","Đào","Mai"] print(flowers[3:])
# in toàn bộ list # int từ phần tử -5 đến -1
print(flowers) print(flowers[-5:-1])
# in phần tử thứ 2 # sửa đổi phần tử
print(flowers[1]) flowers[5]="Súng"
# in phần tử cuối cùng (in lùi thêm dấu "-") print(flowers)
print(flowers[-1])
# in từ phần tử 3-5
print(flowers[3:5])
# in từ đầu 3 phần tử
print(flowers[:3])

Bài 4 Collections trong Python 4


List
• Sử dụng vòng lặp với List

# in các phần tử trong flowers trên dòng # kiểm tra sự tồn tại của phần tử trong List
for f in flowers: if "Mai" in flowers:
print(f) print("Chúc mừng Mai")
# duyệt và lấy ra các flower có chứa chữ a
newflowers=[]
# lấy độ dài List
for f in flowers:
print(len(flowers))
if "a" in f:
newflowers.append(f)
print(newflowers)
# có thể viết rút gọn inline
newflowers=[f for f in flowers if 'a' in f]
print(newflowers)

Bài 4 Collections trong Python 5


List
• Một số các phương thức của List
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Bài 4 Collections trong Python 6


List
• Một số các phương thức của List
# bổ sung, sửa đổi phần tử # copy list
flowers.append("Sen") flowers1=flowers.copy()
print(flowers) print(flowers1)
# chèn phần tử # hoặc cách sau
flowers.insert(1,"Mười giờ") myflowers=list(flowers)
print(flowers) print(myflowers)
# xóa phần tử # nối 2 list
flowers.remove("Súng") specialflowers=["Xoan","Huệ"]
print(flowers) flowerall=flowers+specialflowers
# xóa phần tử cuối print(flowerall)
flowers.pop() # bổ sung list
print(flowers) flowers.extend(specialflowers)
print(flowers)

Bài 4 Collections trong Python 7


List
• Một số các phương thức của List

# sắp xếp các phần tử # xóa phần tử 2


flowers.sort() flowers.pop(2)
print(flowers) print(flowers)
# sắp xếp list tăng / giảm del flowers[2]
flowers.sort() print(flowers)
print(flowers) # xóa hết các phần tử
flowers.sort(reverse=True) flower.clear()
print(flowers) # xóa danh sách
list.sort(flowers) del flowers
print(flowers)
list.sort(flowers,reverse=True)
print(flowers)

Bài 4 Collections trong Python 8


Tuple
• Tuple là một tập hợp có thứ tự nhưng không thể thay đổi, dữ liệu được liệt kê trong
cặp ( ).

# tạo một tuple # in từ phần tử -5 đến -2


companies=("Microsoft","Sun micro system", "IBM","Samsung", print(companies[-5:-2])
"Sony", "Oracle") # chuyển tuple sang list
print(companies) listcom=list(companies)
# in phần tử 1 print(listcom)
print(companies[1]) # thêm giá trị
# in phần tử cuối listcom.append("Apple")
print(companies[-1]) print(listcom)
# in từ phần tử 2 đến 5 # chuyển list sang tuple
print(companies[2:5]) tuplecom=tuple(listcom)
print(tuplecom)

Bài 4 Collections trong Python 9


Tuple
• Vòng lặp với Tuple tương tự List

# vòng lặp # nối 2 tuple


for c in companies: t1=("a","b","c","a","a")
print(c) t2=("1","2","3")
# lấy độ dài tuple t3=t1+t2
print(len(companies)) print(t3)
# tạo tuple có 1 phần tử lưu ý phải có dấu , ở cuối # đếm số lần xuất hiện của 1 giá trị trong 1 bộ
newtuple=("Oppo",) print(t1.count("a"))
print(type(newtuple)) # trả về chỉ số phần tử tìm thấy đầu tiên trong
# xóa tuple tuple
del newtuple print(t1.index("c"))

Bài 4 Collections trong Python 10


Set
• Set là một tập hợp không có thứ tự và không đánh chỉ số, dữ liệu được liệt kê trong
cặp { }.

# tạo một bộ dữ liệu # thêm dữ liệu


phones={"Samsung S20", "Samsung Note 20 Ultra"," phones.add("Mi Note 10 Pro")
Oppo Reno4 Pro", "Mi 10 Pro", "Sony XZ 2"} print(phones)
# hoặc tạo set bằng constructor # thêm một tập dữ liệu
phone1=set(("Samsung S20", "Samsung Note 20 Ultr phones.update({"LG G8","Redmi Note 9","Oppo Reno3"})
a","Oppo Reno4 Pro", "Mi 10 Pro", "Sony XZ 2")) print(phones)
print(phones) # lấy độ dài
# duyệt dữ liệu print(len(phones))
for p in phones: # xóa phần tử, nếu không tồn tại sẽ báo lỗi
print(p) phones.remove("Oppo Reno3")
print(phones)

Bài 4 Collections trong Python 11


Set
# xóa phần tử, nếu không tồn tại thì ko báo lỗi
phones.remove("Oppo Reno3")
print(phones)
# lấy và xóa phần tử cuối cùng
p=phones.pop()
print(p)
print(phones)
# nối 2 tập hợp
newphones={"iPhone 12 Max Pro","iPhone 11 Pro"}
phoneall=phones.union(newphones) # hoặc dùng update như ở trên
print(phoneall)
# xóa hết phần tử trong set
phones.clear()
# xóa set
del phones

Bài 4 Collections trong Python 12


Dictionary
• Dictionary là một tập hợp không có thứ tự, có thể thay đổi và đánh chỉ mục, mỗi phần
tử gồm key và value và được liệt kê trong cặp { }

# tạo một dictionary # sửa dữ liệu


car = { car["price"]=1220
"carno":"CM200012", print(car)
"brand":"Toyota", # duyệt và in ra key:value
"model":"Innova", for key in car:
"price":1200 print(key,":",car[key])
} for x, y in car.items():
# hoặc dùng constructor print(x,":", y)
car1=dict(carno="CM200014",brand="Toyota",model="Vios", # kiểm tra sự tồn tại của key
price=1100) if "model" in car:
print(car) print("Có tồn tại key model")

Bài 4 Collections trong Python 13


Dictionary
# thêm dữ liệu # tạo dictionary lồng nhau
car["year"]=2016 students={
print(car) "st1":{
# copy dictionary "name":"Nguyễn Văn Hưng",
dic=car.copy() "phone":"0987678904"
print(dic) },
# xóa item theo key "st2": {
car.pop("model") "name":"Lê Minh Tùng",
print(car) "phone":"0987654356"
# hoặc, báo lỗi khi key không tồn tại },
del car["model"] "st3":{
# xóa sạch dữ liệu bên trong "name":"Trần Thi Thảo",
car.clear() "phone":"0987654346"
# xóa dictionary }
del car }

Bài 4 Collections trong Python 14


HỎI ĐÁP

Bài 4 Collections trong Python 15


TRẢI NGHIỆM THỰC HÀNH
Bài 4 Collections trong Python 16
HỆ THỐNG ĐÀO TẠO CNTT QUỐC TẾ BACHKHOA - APTECH

238 Hoàng Quốc Việt, Bắc Từ Liêm, Hà Nội

0968.27.6996

tuyensinh@bachkhoa-aptech.edu.vn

www.bachkhoa-aptech.edu.vn

Bài 4 Collections trong Python 17

You might also like