28.04.2020 Views

Sách Deep Learning cơ bản

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

30 Chương 2. Python cơ bản

t = True

f = False

print(type(t)) # Prints "<class 'bool'>"

print(t and f) # AND; prints "False"

print(t or f) # OR; prints "True"

print(not t) # NOT; prints "False"

print(t != f) # XOR; prints "True"

2.1.3 Chuỗi

Python có hỗ trợ dạng chuỗi

hello = 'hello' # gán giá trị chuỗi cho biến, chuỗi đặt trong 2 dấu '

world = "world" # chuỗi cũng có thể đặt trong dấu ".

print(hello) # Prints "hello"

print(len(hello)) # Độ dài chuỗi; prints "5"

hw = hello + ' ' + world # Nối chuỗi bằng dấu +

print(hw) # prints "hello world"

hw12 = '%s %s %d' % (hello, world, 12) # Cách format chuỗi

print(hw12) # prints "hello world 12"

Kiểu string có rất nhiều method để xử lý chuỗi

s = "hello"

print(s.capitalize()) # Viết hoa chữ cái đầu; prints "Hello"

print(s.upper()) # Viết hoa tất cả các chữ; prints "HELLO"

print(s.replace('l', '(ell)')) # Thay thế chuỗi; prints "he(ell)(ell)o"

print(' world '.strip()) # Bỏ đi khoảng trắng ở đầu và cuối chuỗi; prints "world"

2.2 Containers

2.2.1 List

Python có một số container như: lists, dictionaries,...

List trong Python giống như mảng (array) nhưng không cố định kích thước và có thể chứa nhiều

kiểu dữ liệu khác nhau trong 1 list.

xs = [3, 1, 2] # Tạo 1 list

print(xs, xs[2]) # Prints "[3, 1, 2] 2"

print(xs[-1]) # Chỉ số âm là đếm phần tử từ cuối list lên; prints "2"

xs[2] = 'foo' # List có thể chứa nhiều kiểu phần tử khác nhau

print(xs) # Prints "[3, 1, 'foo']"

xs.append('bar') # Thêm phần tử vào cuối list

print(xs) # Prints "[3, 1, 'foo', 'bar']"

x = xs.pop() # Bỏ đi phần tử cuối cùng khỏi list và trả về phần tử đấy

print(x, xs) # Prints "bar [3, 1, 'foo']"

Slicing Thay vì lấy từng phần tử một trong list thì python hỗ trợ truy xuất nhiều phần tử 1 lúc gọi là

slicing.

nums = list(range(5)) # range sinh ta 1 list các phần tử

print(nums) # Prints "[0, 1, 2, 3, 4]"

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!