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.
2.3 Function 31
print(nums[2:4]) # Lấy phần tử thứ 2->4, python chỉ số mảng từ 0;
print(nums[2:]) # Lấy từ phần tử thứ 2 đến hết; prints "[2, 3, 4]"
print(nums[:2]) # Lấy từ đầu đến phần tử thứ 2; prints "[0, 1]"
print(nums[:]) # Lấy tất cả phần tử trong list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1]) # Lấy từ phần tử đầu đến phần tử gần cuối trong list; prints "[0
nums[2:4] = [8, 9] # Gán giá trị mới cho phần tử trong mảng từ vị trí 2->4
print(nums) # Prints "[0, 1, 8, 9, 4]"
Loops Để duyệt và in ra các phần tử trong list
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", in mỗi thành phần trong list 1 dòng
2.2.2 Dictionaries
Dictionaries lưu thông tin dưới dạng key, value.
d = {'cat': 'cute', 'dog': 'furry'} # Tạo dictionary, các phần tử dạng key:value
print(d['cat']) # Lấy ra value của key 'cat' trong dictionary; prints "cute"
print('cat' in d) # Kiểm tra key có trong dictionary không; prints "True"
d['fish'] = 'wet' # Gán key, value, d[key] = value
print(d['fish']) # Prints "wet"
# print(d['monkey']) # Lỗi vì key 'monkey' không trong dictionary;
del d['fish'] # Xóa phần tử key:value từ dictionary
Loop Duyệt qua các phần tử trong dictionary
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
2.3 Function
Function là một khối code python được thực hiện một hoặc một số chức năng nhất định. Function
trong python được định nghĩa với keyword def.
# Hàm có input là 1 số và output xem số đấy âm, dương hay số 0
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print(sign(x))
# Prints "negative", "zero", "positive"