Hướng dẫn is dictionary a data type or data structure in python? - từ điển là kiểu dữ liệu hay cấu trúc dữ liệu trong python?

Hướng dẫn is dictionary a data type or data structure in python? - từ điển là kiểu dữ liệu hay cấu trúc dữ liệu trong python?

Từ điển là một trong những cấu trúc dữ liệu được sử dụng nhiều nhất trong Python. Một từ điển là một bộ sưu tập các mục không đặt hàng và chúng tôi thường có các khóa và giá trị được lưu trữ trong một từ điển. Chúng ta hãy xem xét một vài ví dụ về cách từ điển thường được sử dụng.

# dictionary declaration 1
dict1 = dict()

# dictionary declaration 2
dict2 = {}

# Add items to the dictionary
# The syntax to add and retrieve items is same for either of the two objects we defined above. 
key = "X"
value = "Y"
dict1[key] = value

# The dictionary doesn't have any specific data-type. 
# So, the values can be pretty diverse. 
dict1[key] = dict2

Bây giờ hãy nhìn vào một số cách truy xuất.

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]

Tránh KeyError: Sử dụng. Chức năng

Trong trường hợp khóa đã cho không tồn tại trong từ điển, Python sẽ ném

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
1. Có một cách giải quyết đơn giản cho điều này. Hãy cùng xem xét cách chúng ta có thể tránh
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
1 bằng cách sử dụng hàm
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
3 được xây dựng cho từ điển.

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))

Rất nhiều lần chúng tôi ổn khi nhận được một giá trị mặc định khi khóa không tồn tại. Ví dụ: Khi xây dựng một quầy. Có một cách tốt hơn để có được các giá trị mặc định từ từ điển trong trường hợp các khóa bị thiếu thay vì dựa vào tiêu chuẩn

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
4.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1

Vì vậy,

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
5 là một hoạt động tiện dụng để truy xuất giá trị mặc định cho bất kỳ khóa nào từ từ điển. Vấn đề với phương pháp này xảy ra khi chúng ta muốn xử lý các cấu trúc dữ liệu có thể thay đổi dưới dạng các giá trị, ví dụ:
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
6 hoặc
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
7.

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}

Bạn có thấy vấn đề không?

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
7 mới hoặc
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
6 không được gán cho khóa từ điển. Chúng ta nên gán một
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
6 hoặc
dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
7 mới cho khóa trong trường hợp thiếu giá trị và sau đó tương ứng
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
2 hoặc
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
3. Ley sườn nhìn vào một ví dụ cho điều này.

dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!

Tránh KeyError: Sử dụng DefaultDict

Điều này hoạt động hầu hết thời gian. Tuy nhiên, có một cách tốt hơn để làm điều này. Một cách

dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
4 hơn.
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
5 là một lớp con của lớp Dict tích hợp.
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
5 chỉ cần gán giá trị mặc định mà chúng tôi chỉ định trong trường hợp khóa bị thiếu. Vì vậy, hai bước:

dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")

Bây giờ có thể được kết hợp thành một bước duy nhất. Ví dụ:

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(, {'random_key': ['Hello World!']}) 
  defaultdict(, {'random_key': {'Hello World!'}}) 
  defaultdict(, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)

Tài liệu chính thức


Học mã miễn phí. Chương trình giảng dạy nguồn mở của Freecodecamp đã giúp hơn 40.000 người có được việc làm với tư cách là nhà phát triển. Bắt đầu

Chương này mô tả một số điều mà bạn đã học được về chi tiết hơn và thêm một số điều mới.

5.1. Thêm về Danh sáchMore on Lists¶

Kiểu dữ liệu danh sách có một số phương pháp khác. Dưới đây là tất cả các phương thức của các đối tượng danh sách:

________ 57 ________ 52 (x)(x)

Thêm một mục vào cuối danh sách. Tương đương với

dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
9.

________ 57 ________ 61 (có thể lặp lại)(iterable)

Mở rộng danh sách bằng cách nối thêm tất cả các mục từ Itable. Tương đương với

dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
2.

________ 57 ________ 64 (i, x)(i, x)

Chèn một mục tại một vị trí nhất định. Đối số đầu tiên là chỉ số của phần tử trước đó để chèn, do đó

dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
5 chèn ở phía trước của danh sách và
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
6 tương đương với
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
7.

________ 57 ________ 69 (x)(x)

Xóa mục đầu tiên khỏi danh sách có giá trị bằng x. Nó tăng một

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(, {'random_key': ['Hello World!']}) 
  defaultdict(, {'random_key': {'Hello World!'}}) 
  defaultdict(, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
0 nếu không có mặt hàng như vậy.

________ 57 ________ 72 ([i])([i])

Loại bỏ mục tại vị trí đã cho trong danh sách và trả về nó. Nếu không có chỉ mục được chỉ định,

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(, {'random_key': ['Hello World!']}) 
  defaultdict(, {'random_key': {'Hello World!'}}) 
  defaultdict(, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
3 sẽ xóa và trả về mục cuối cùng trong danh sách. .

________ 57 ________ 75 ()()

Xóa tất cả các mục khỏi danh sách. Tương đương với

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(, {'random_key': ['Hello World!']}) 
  defaultdict(, {'random_key': {'Hello World!'}}) 
  defaultdict(, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
6.

________ 57 ________ 78 (x [, bắt đầu [, kết thúc]]))(x[, start[, end]])

Trả về chỉ mục dựa trên 0 trong danh sách mục đầu tiên có giá trị bằng x. Tăng

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(, {'random_key': ['Hello World!']}) 
  defaultdict(, {'random_key': {'Hello World!'}}) 
  defaultdict(, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
0 nếu không có mặt hàng như vậy.

Các đối số tùy chọn bắt đầu và kết thúc được giải thích là trong ký hiệu lát cắt và được sử dụng để giới hạn tìm kiếm ở một phần trăm cụ thể của danh sách. Chỉ số được trả về được tính toán liên quan đến đầu của chuỗi đầy đủ thay vì đối số bắt đầu.

________ 57 ________ 81 (x)(x)

Trả về số lần x xuất hiện trong danh sách.

________ 57 ________ 83 (*, key = none, lùi = sai)(*, key=None, reverse=False)

Sắp xếp các mục của danh sách tại chỗ (các đối số có thể được sử dụng để sắp xếp sắp xếp, xem

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
4 để giải thích của họ).

________ 57 ________ 86 ()()

Đảo ngược các yếu tố của danh sách tại chỗ.

________ 57 ________ 88 ()()

Trả lại một bản sao nông của danh sách. Tương đương với

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
9.

Một ví dụ sử dụng hầu hết các phương thức danh sách:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

Bạn có thể nhận thấy rằng các phương thức như

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
0,
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
1 hoặc
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
2 chỉ sửa đổi danh sách không có giá trị trả về được in - chúng trả lại mặc định
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
3 mặc định. 1 Đây là một nguyên tắc thiết kế cho tất cả các cấu trúc dữ liệu có thể thay đổi trong Python.

Một điều khác bạn có thể nhận thấy là không phải tất cả dữ liệu có thể được sắp xếp hoặc so sánh. Chẳng hạn,

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
4 không sắp xếp vì các số nguyên có thể được so sánh với các chuỗi và không ai có thể so sánh với các loại khác. Ngoài ra, có một số loại don don có mối quan hệ đặt hàng xác định. Ví dụ,
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5 là một so sánh hợp lệ.

5.1.1. Sử dụng danh sách như Stacks¶Using Lists as Stacks¶

Các phương thức danh sách giúp việc sử dụng danh sách như một ngăn xếp rất dễ dàng, trong đó phần tử cuối cùng được thêm vào là phần tử đầu tiên được truy xuất (lần cuối cùng, lần đầu tiên, ra mắt). Để thêm một mục vào đầu ngăn xếp, hãy sử dụng

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
6. Để lấy một mục từ đầu ngăn xếp, hãy sử dụng
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
7 mà không có chỉ mục rõ ràng. Ví dụ:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

5.1.2. Sử dụng danh sách như hàng đợiUsing Lists as Queues¶

Cũng có thể sử dụng một danh sách như một hàng đợi, trong đó phần tử đầu tiên được thêm vào là phần tử đầu tiên được truy xuất (từ đầu tiên, lần đầu tiên); Tuy nhiên, danh sách không hiệu quả cho mục đích này. Mặc dù các lần nối và bật từ cuối danh sách rất nhanh, nhưng việc chèn hoặc bật từ đầu danh sách là chậm (vì tất cả các yếu tố khác phải được thay đổi bởi một).

Để thực hiện hàng đợi, hãy sử dụng

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
8 được thiết kế để có sự thay đổi nhanh chóng và bật từ cả hai đầu. Ví dụ:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
0

5.1.3. Danh sách toàn diệnList Comprehensions¶

Danh sách toàn diện cung cấp một cách ngắn gọn để tạo danh sách. Các ứng dụng phổ biến là tạo ra các danh sách mới trong đó mỗi yếu tố là kết quả của một số hoạt động được áp dụng cho từng thành viên của một chuỗi khác hoặc có thể lặp lại hoặc tạo ra một phần trăm của các yếu tố đáp ứng một điều kiện nhất định.

Ví dụ: giả sử chúng tôi muốn tạo một danh sách các ô vuông, như:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
1

Lưu ý rằng điều này tạo ra (hoặc ghi đè) một biến có tên

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
9 vẫn tồn tại sau khi vòng lặp hoàn thành. Chúng ta có thể tính toán danh sách các ô vuông mà không cần bất kỳ tác dụng phụ nào bằng cách sử dụng:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
2

Hoặc, tương đương:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
3

đó là ngắn gọn và dễ đọc hơn.

Một danh sách hiểu bao gồm các dấu ngoặc chứa một biểu thức theo sau là mệnh đề

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
00, sau đó không hoặc nhiều hơn
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
00 hoặc
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
02. Kết quả sẽ là một danh sách mới do đánh giá biểu thức trong bối cảnh của các điều khoản
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
00 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
02 theo nó. Ví dụ, ListComp này kết hợp các yếu tố của hai danh sách nếu chúng không bằng nhau:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
4

Và nó tương đương với:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
5

Lưu ý cách thứ tự của các câu lệnh

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
00 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
02 giống nhau trong cả hai đoạn này.

Nếu biểu thức là một tuple (ví dụ:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
07 trong ví dụ trước), nó phải được đặt dấu ngoặc đơn.

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
6

Danh sách các hệ thống có thể chứa các biểu thức phức tạp và các hàm lồng nhau:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
7

5.1.4. Danh sách lồng nhau toàn diệnNested List Comprehensions¶

Biểu thức ban đầu trong khả năng hiểu danh sách có thể là bất kỳ biểu thức tùy ý nào, bao gồm cả sự hiểu biết danh sách khác.

Hãy xem xét ví dụ sau đây của ma trận 3x4 được triển khai dưới dạng danh sách 3 danh sách độ dài 4:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
8

Danh sách hiểu biết sau đây sẽ chuyển đổi các hàng và cột:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
9

Như chúng ta đã thấy trong phần trước, ListComp lồng nhau được đánh giá trong bối cảnh của

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
00 theo sau, vì vậy ví dụ này tương đương với:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
0

Điều này, đến lượt nó, giống như:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
1

Trong thế giới thực, bạn nên thích các chức năng tích hợp hơn cho các câu lệnh dòng chảy phức tạp. Hàm

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
09 sẽ làm rất tốt cho trường hợp sử dụng này:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
2

Xem danh sách đối số giải nén để biết chi tiết về dấu hoa thị trong dòng này.Unpacking Argument Lists for details on the asterisk in this line.

5.2. Tuyên bố # Since "X" exists in our dictionary, this will retrieve the value value = dict1[key] # This key doesn't exist in the dictionary. # So, we will get a `KeyError` value = dict1["random"]10The # Since "X" exists in our dictionary, this will retrieve the value value = dict1[key] # This key doesn't exist in the dictionary. # So, we will get a `KeyError` value = dict1["random"]10 statement¶

Có một cách để xóa một mục khỏi danh sách được đưa ra chỉ mục của nó thay vì giá trị của nó: câu lệnh

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
10. Điều này khác với phương thức
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
7 trả về giá trị. Câu lệnh
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
10 cũng có thể được sử dụng để xóa các lát khỏi danh sách hoặc xóa toàn bộ danh sách (mà chúng tôi đã làm trước đó bằng cách gán một danh sách trống cho lát cắt). Ví dụ:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
3

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
10 cũng có thể được sử dụng để xóa toàn bộ biến:

Tham khảo tên

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
15 sau đây là một lỗi (ít nhất là cho đến khi một giá trị khác được gán cho nó). Chúng tôi sẽ tìm thấy các công dụng khác cho
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
10 sau.

5.3. Tuples and Streak¶Tuples and Sequences¶

Chúng tôi đã thấy rằng các danh sách và chuỗi có nhiều thuộc tính chung, chẳng hạn như các hoạt động lập chỉ mục và cắt lát. Chúng là hai ví dụ về các loại dữ liệu chuỗi (xem các loại trình tự - danh sách, tuple, phạm vi). Vì Python là một ngôn ngữ phát triển, các loại dữ liệu trình tự khác có thể được thêm vào. Ngoài ra còn có một loại dữ liệu trình tự tiêu chuẩn khác: Tuple.Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

Một tuple bao gồm một số giá trị được phân tách bằng dấu phẩy, ví dụ:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
4

Như bạn thấy, trên các bộ dữ liệu đầu ra luôn được đặt trong ngoặc đơn, do đó các bộ dữ liệu lồng nhau được giải thích chính xác; Chúng có thể là đầu vào có hoặc không có dấu ngoặc đơn xung quanh, mặc dù dù sao cũng thường là dấu ngoặc đơn (nếu tuple là một phần của biểu thức lớn hơn). Không thể gán cho các mục riêng lẻ của một tuple, tuy nhiên có thể tạo các bộ dữ liệu có chứa các đối tượng có thể thay đổi, chẳng hạn như danh sách.

Mặc dù các bộ dữ liệu có vẻ giống với danh sách, nhưng chúng thường được sử dụng trong các tình huống khác nhau và cho các mục đích khác nhau. Các bộ dữ liệu là bất biến và thường chứa một chuỗi các yếu tố không đồng nhất được truy cập thông qua việc giải nén (xem sau trong phần này) hoặc lập chỉ mục (hoặc thậm chí bởi thuộc tính trong trường hợp

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
17). Danh sách có thể thay đổi, và các yếu tố của chúng thường đồng nhất và được truy cập bằng cách lặp lại trong danh sách.immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
17). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Một vấn đề đặc biệt là việc xây dựng các bộ dữ liệu chứa 0 hoặc 1 mục: cú pháp có thêm một số quirks để phù hợp với những thứ này. Các bộ dữ liệu trống được xây dựng bởi một cặp dấu ngoặc đơn trống; Một tuple với một mục được xây dựng bằng cách làm theo giá trị bằng dấu phẩy (không đủ để gửi một giá trị duy nhất trong ngoặc đơn). Xấu xí, nhưng hiệu quả. Ví dụ:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
5

Tuyên bố

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
18 là một ví dụ về đóng gói tple: các giá trị
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
19,
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
20 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
21 được đóng gói với nhau trong một tuple. Hoạt động ngược cũng có thể:

Điều này được gọi, đủ thích hợp, giải nén trình tự và hoạt động cho bất kỳ chuỗi nào ở phía bên phải. Trình tự giải nén yêu cầu có nhiều biến ở phía bên trái của dấu bằng như có các phần tử trong chuỗi. Lưu ý rằng nhiều bài tập thực sự chỉ là sự kết hợp của việc đóng gói và giải nén trình tự.

5.4. ĐặtSets¶

Python cũng bao gồm một loại dữ liệu cho các bộ. Một bộ là một bộ sưu tập không có thứ tự không có yếu tố trùng lặp. Sử dụng cơ bản bao gồm kiểm tra thành viên và loại bỏ các mục trùng lặp. Đặt các đối tượng cũng hỗ trợ các hoạt động toán học như liên minh, giao lộ, sự khác biệt và sự khác biệt đối xứng.

Niềng răng xoăn hoặc hàm

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
22 có thể được sử dụng để tạo các bộ. Lưu ý: Để tạo một bộ trống, bạn phải sử dụng
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
22, không phải
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
24; Cái sau tạo ra một từ điển trống, một cấu trúc dữ liệu mà chúng ta thảo luận trong phần tiếp theo.

Đây là một cuộc biểu tình ngắn gọn:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
6

Tương tự như danh sách toàn diện, bộ toàn diện cũng được hỗ trợ:list comprehensions, set comprehensions are also supported:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
7

5.5. Từ điển bàiDictionaries¶

Một loại dữ liệu hữu ích khác được tích hợp vào Python là từ điển (xem các loại ánh xạ - dict). Từ điển đôi khi được tìm thấy trong các ngôn ngữ khác như là ký ức liên kết của người Hồi giáo hoặc các mảng liên kết của người Hồi giáo. Không giống như các chuỗi, được lập chỉ mục bởi một loạt các số, từ điển được lập chỉ mục bởi các khóa, có thể là bất kỳ loại bất biến; Chuỗi và số luôn có thể là chìa khóa. Bộ dữ liệu có thể được sử dụng làm khóa nếu chúng chỉ chứa chuỗi, số hoặc bộ dữ liệu; Nếu một tuple chứa bất kỳ đối tượng có thể thay đổi trực tiếp hoặc gián tiếp, nó không thể được sử dụng làm khóa. Bạn có thể sử dụng danh sách làm khóa làm khóa, vì danh sách có thể được sửa đổi tại chỗ bằng cách sử dụng các bài tập chỉ mục, bài tập lát cắt hoặc các phương thức như

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
6 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
26.Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
6 and
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
26.

Tốt nhất là nghĩ về một từ điển như một tập hợp các khóa: các cặp giá trị, với yêu cầu rằng các khóa là duy nhất (trong một từ điển). Một cặp niềng răng tạo ra một từ điển trống:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
24. Đặt một danh sách phân tách bằng dấu phẩy: các cặp giá trị trong niềng răng thêm khóa ban đầu: các cặp giá trị vào từ điển; Đây cũng là cách từ điển được viết trên đầu ra.

Các hoạt động chính trên từ điển đang lưu trữ một giá trị với một số khóa và trích xuất giá trị được đưa ra khóa. Cũng có thể xóa một cặp khóa: giá trị với

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
10. Nếu bạn lưu trữ bằng cách sử dụng một khóa đã được sử dụng, giá trị cũ được liên kết với khóa đó sẽ bị lãng quên. Đó là một lỗi để trích xuất một giá trị bằng cách sử dụng khóa không tồn tại.

Thực hiện

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
29 trên một từ điển trả về danh sách tất cả các khóa được sử dụng trong từ điển, theo thứ tự chèn (nếu bạn muốn nó được sắp xếp, chỉ cần sử dụng
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
30 thay thế). Để kiểm tra xem một khóa duy nhất có trong từ điển hay không, hãy sử dụng từ khóa
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
31.

Dưới đây là một ví dụ nhỏ bằng cách sử dụng từ điển:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
8

Hàm tạo

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
32 xây dựng từ điển trực tiếp từ các chuỗi của các cặp giá trị khóa:

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))
9

Ngoài ra, các toàn bộ Dict có thể được sử dụng để tạo từ điển từ các biểu thức chính và giá trị tùy ý:

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
0

Khi các phím là các chuỗi đơn giản, đôi khi việc chỉ định các cặp bằng các đối số từ khóa sẽ dễ dàng hơn:

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
1

5.6. Kỹ thuật lặp lạiLooping Techniques¶

Khi lặp qua từ điển, khóa và giá trị tương ứng có thể được truy xuất cùng một lúc bằng phương pháp

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
33.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
2

Khi lặp qua một chuỗi, chỉ số vị trí và giá trị tương ứng có thể được truy xuất cùng một lúc bằng cách sử dụng hàm

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
34.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
3

Để lặp qua hai hoặc nhiều chuỗi cùng một lúc, các mục có thể được ghép nối với hàm

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
09.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
4

Để lặp qua một chuỗi ngược lại, trước tiên chỉ định chuỗi theo hướng chuyển tiếp và sau đó gọi hàm

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
36.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
5

Để lặp qua một chuỗi theo thứ tự được sắp xếp, hãy sử dụng hàm

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
4 trả về một danh sách được sắp xếp mới trong khi để lại nguồn không thay đổi.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
6

Sử dụng

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
22 trên một chuỗi loại bỏ các phần tử trùng lặp. Việc sử dụng
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
4 kết hợp với
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
22 qua một chuỗi là một cách thành ngữ để lặp lại các yếu tố duy nhất của chuỗi theo thứ tự được sắp xếp.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
7

Đôi khi thật hấp dẫn khi thay đổi một danh sách trong khi bạn đang lặp lại nó; Tuy nhiên, thay vào đó, nó thường đơn giản và an toàn hơn để tạo một danh sách mới.

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
8

5.7. Thêm về điều kiện lorMore on Conditions¶

Các điều kiện được sử dụng trong các câu lệnh

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
41 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
02 có thể chứa bất kỳ toán tử nào, không chỉ so sánh.

Các toán tử so sánh

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
31 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
44 là các thử nghiệm thành viên xác định xem một giá trị có ở (hoặc không) một container hay không. Các toán tử
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
45 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
46 so sánh xem hai đối tượng có thực sự là cùng một đối tượng hay không. Tất cả các toán tử so sánh có cùng mức độ ưu tiên, thấp hơn so với tất cả các toán tử số.

So sánh có thể được xích. Ví dụ:

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
47 kiểm tra xem
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
15 có nhỏ hơn
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
49 và hơn nữa
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
49 bằng
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
51.

So sánh có thể được kết hợp bằng cách sử dụng các toán tử boolean

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
52 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
53, và kết quả của một so sánh (hoặc của bất kỳ biểu thức boolean nào khác) có thể bị phủ định với
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
54. Chúng có các ưu tiên thấp hơn các nhà khai thác so sánh; Giữa họ,
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
54 có mức ưu tiên cao nhất và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
53 thấp nhất, do đó
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
57 tương đương với
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
58. Như mọi khi, dấu ngoặc đơn có thể được sử dụng để thể hiện thành phần mong muốn.

Các toán tử Boolean

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
52 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
53 được gọi là toán tử ngắn mạch: đối số của họ được đánh giá từ trái sang phải và việc đánh giá dừng ngay khi kết quả được xác định. Ví dụ: nếu
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
61 và
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
62 là đúng nhưng
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
63 là sai,
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
64 không đánh giá biểu thức
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
62. Khi được sử dụng làm giá trị chung và không phải là boolean, giá trị trả về của toán tử ngắn mạch là đối số được đánh giá cuối cùng.

Có thể gán kết quả so sánh hoặc biểu thức boolean khác cho một biến. Ví dụ,

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1
9

Lưu ý rằng trong Python, không giống như C, việc gán bên trong các biểu thức phải được thực hiện rõ ràng với toán tử Walrus

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
66. Điều này tránh được một nhóm vấn đề phổ biến gặp phải trong các chương trình C: gõ
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
67 trong một biểu thức khi
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
68 được dự định.walrus operator
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
66. This avoids a common class of problems encountered in C programs: typing
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
67 in an expression when
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
68 was intended.

5,8. So sánh trình tự và các loại khácComparing Sequences and Other Types¶

Các đối tượng trình tự thường có thể được so sánh với các đối tượng khác có cùng loại trình tự. Việc so sánh sử dụng thứ tự từ vựng: đầu tiên hai mục đầu tiên được so sánh và nếu chúng khác nhau thì điều này sẽ xác định kết quả của so sánh; Nếu chúng bằng nhau, hai mục tiếp theo được so sánh, v.v., cho đến khi một trong hai chuỗi bị cạn kiệt. Nếu hai mục được so sánh là các chuỗi cùng loại, so sánh từ vựng được thực hiện đệ quy. Nếu tất cả các mục của hai chuỗi so sánh bằng nhau, các chuỗi được coi là bằng nhau. Nếu một chuỗi là một chuỗi con ban đầu của bảng khác, trình tự ngắn hơn là phần nhỏ hơn (nhỏ hơn). Đặt hàng từ vựng cho các chuỗi sử dụng số điểm mã Unicode để đặt hàng các ký tự riêng lẻ. Một số ví dụ về so sánh giữa các chuỗi cùng loại:

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
0

Lưu ý rằng việc so sánh các đối tượng thuộc các loại khác nhau với

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
69 hoặc
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
70 là hợp pháp với điều kiện là các đối tượng có các phương pháp so sánh phù hợp. Ví dụ, các loại số hỗn hợp được so sánh theo giá trị số của chúng, do đó 0 bằng 0,0, v.v. Nếu không, thay vì cung cấp một thứ tự tùy ý, trình thông dịch sẽ tăng ngoại lệ
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
71.

Chú thích

1

Các ngôn ngữ khác có thể trả về đối tượng đột biến, cho phép chuỗi phương thức, chẳng hạn như

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]
72.

Từ điển có phải là cấu trúc dữ liệu hay kiểu dữ liệu không?

Từ điển là một cấu trúc dữ liệu có mục đích chung để lưu trữ một nhóm các đối tượng. Một từ điển có một bộ các khóa và mỗi khóa có một giá trị liên quan duy nhất.data structure for storing a group of objects. A dictionary has a set of keys and each key has a single associated value.

Kiểu dữ liệu từ điển trong Python là gì?

Từ điển.Từ điển được sử dụng để lưu trữ các giá trị dữ liệu trong khóa: các cặp giá trị.Từ điển là một bộ sưu tập được đặt hàng*, có thể thay đổi và không cho phép trùng lặp.Kể từ phiên bản Python 3.7, từ điển được đặt hàng.Trong Python 3.6 và trước đó, từ điển không được đặt hàng.used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Từ điển dữ liệu trong cấu trúc dữ liệu là gì?

Từ điển dữ liệu là một tập hợp các tên, định nghĩa và thuộc tính về các yếu tố dữ liệu đang được sử dụng hoặc nắm bắt trong cơ sở dữ liệu, hệ thống thông tin hoặc một phần của dự án nghiên cứu.a collection of names, definitions, and attributes about data elements that are being used or captured in a database, information system, or part of a research project.

Kiểu dữ liệu từ điển có được hỗ trợ trong Python không?

Từ điển trong Python Hầu như bất kỳ loại giá trị nào cũng có thể được sử dụng làm khóa từ điển trong Python.Bạn thậm chí có thể sử dụng các đối tượng tích hợp như các loại và chức năng.Tuy nhiên, có một vài hạn chế rằng các khóa từ điển phải tuân thủ.Đầu tiên, một khóa nhất định chỉ có thể xuất hiện trong một từ điển một lần.