Hướng dẫn what is collections library in python? - thư viện bộ sưu tập trong python là gì?
Mã nguồn: lib/bộ sưu tập/__ init__.py Lib/collections/__init__.py Show
Mô-đun này thực hiện các kiểu dữ liệu container chuyên dụng cung cấp các lựa chọn thay thế cho các thùng chứa tích hợp mục đích chung của Python, c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4, c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5, c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary6 và c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary7.
class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 0 Đối tượngMới trong phiên bản 3.3. Một lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 được cung cấp để nhanh chóng liên kết một số ánh xạ để chúng có thể được coi là một đơn vị. Nó thường nhanh hơn nhiều so với việc tạo một từ điển mới và chạy nhiều cuộc gọi class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})9. Lớp có thể được sử dụng để mô phỏng phạm vi lồng nhau và rất hữu ích trong việc tạo khuôn mẫu. Lớp ________ 60 ________ 61 (*Bản đồ) ¶(*maps)¶Một nhóm class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 nhiều bản đồ hoặc ánh xạ khác lại với nhau để tạo một chế độ xem duy nhất, có thể cập nhật. Nếu không có bản đồ nào được chỉ định, một từ điển trống duy nhất được cung cấp để một chuỗi mới luôn có ít nhất một ánh xạ. Các ánh xạ cơ bản được lưu trữ trong một danh sách. Danh sách đó là công khai và có thể được truy cập hoặc cập nhật bằng thuộc tính MAPS. Không có nhà nước nào khác. Tra cứu tìm kiếm các ánh xạ cơ bản liên tiếp cho đến khi tìm thấy chìa khóa. Ngược lại, ghi, cập nhật và xóa chỉ hoạt động trên bản đồ đầu tiên. A class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 kết hợp các ánh xạ cơ bản bằng cách tham khảo. Vì vậy, nếu một trong những ánh xạ cơ bản được cập nhật, những thay đổi đó sẽ được phản ánh trong class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0. Tất cả các phương pháp từ điển thông thường được hỗ trợ. Ngoài ra, có một thuộc tính MAPS, một phương thức để tạo các phân nhóm mới và một thuộc tính để truy cập tất cả trừ ánh xạ đầu tiên: ________ 65¶Một danh sách có thể cập nhật của người dùng các ánh xạ. Danh sách được đặt hàng từ lần đầu tiên được tìm kiếm để tìm kiếm cuối cùng. Đây là trạng thái duy nhất được lưu trữ và có thể được sửa đổi để thay đổi ánh xạ nào được tìm kiếm. Danh sách phải luôn luôn chứa ít nhất một ánh xạ. ________ 66 (m = không, ** kwargs) ¶(m=None, **kwargs)¶Trả về một class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 mới chứa một bản đồ mới, sau đó là tất cả các bản đồ trong trường hợp hiện tại. Nếu >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) >>> # Find the ten most common words in Hamlet >>> import re >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]8 được chỉ định, nó sẽ trở thành bản đồ mới ở phía trước danh sách các ánh xạ; Nếu không được chỉ định, một dict trống được sử dụng, do đó, một cuộc gọi đến >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) >>> # Find the ten most common words in Hamlet >>> import re >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]9 tương đương với: >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args0. Nếu bất kỳ đối số từ khóa nào được chỉ định, họ sẽ cập nhật bản đồ thông qua hoặc Dict New Dict mới. Phương pháp này được sử dụng để tạo các phân nhóm có thể được cập nhật mà không thay đổi các giá trị trong bất kỳ ánh xạ cha mẹ nào. Đã thay đổi trong phiên bản 3.4: Tham số >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) >>> # Find the ten most common words in Hamlet >>> import re >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]8 parameter was added. Thay đổi trong phiên bản 3.10: Hỗ trợ đối số từ khóa đã được thêm vào.Keyword arguments support was added. ________ 72¶Thuộc tính Trả về một class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 mới chứa tất cả các bản đồ trong trường hợp hiện tại ngoại trừ cái đầu tiên. Điều này rất hữu ích để bỏ qua bản đồ đầu tiên trong tìm kiếm. Các trường hợp sử dụng tương tự như từ khóa >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args4 được sử dụng trong phạm vi lồng nhau. Các trường hợp sử dụng cũng song song với chức năng >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args5 tích hợp. Một tham chiếu đến >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args6 tương đương với: >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args7.nested scopes. The use cases also parallel those for the built-in >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args5 function. A reference to >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args6 is equivalent to: >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args7. Lưu ý, thứ tự lặp của >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args8 được xác định bằng cách quét các ánh xạ cuối cùng đến đầu tiên: >>> baseline = {'music': 'bach', 'art': 'rembrandt'} >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'} >>> list(ChainMap(adjustments, baseline)) ['music', 'art', 'opera'] Điều này đưa ra thứ tự tương tự như một loạt các cuộc gọi >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args9 bắt đầu bằng ánh xạ cuối cùng: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera'] Đã thay đổi trong phiên bản 3.9: Đã thêm hỗ trợ cho các toán tử >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 00 and >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 01 operators, specified in PEP 584. Xem thêm
class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 0 ví dụ và công thức nấu ănPhần này cho thấy các cách tiếp cận khác nhau để làm việc với các bản đồ chuỗi. Ví dụ về mô phỏng chuỗi tra cứu nội bộ Python: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins)) Ví dụ về việc cho phép các đối số dòng lệnh do người dùng chỉ định được ưu tiên hơn các biến môi trường, lần lượt được ưu tiên hơn các giá trị mặc định: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user']) Các mẫu ví dụ để sử dụng lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 để mô phỏng bối cảnh lồng nhau: c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary Lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})0 chỉ thực hiện các bản cập nhật (ghi và xóa) vào ánh xạ đầu tiên trong chuỗi trong khi tra cứu sẽ tìm kiếm toàn bộ chuỗi. Tuy nhiên, nếu mong muốn ghi và xóa sâu, thật dễ dàng để tạo một lớp con cập nhật các khóa được tìm thấy sâu hơn trong chuỗi: class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 1 Đối tượngMột công cụ truy cập được cung cấp để hỗ trợ các số lượng thuận tiện và nhanh chóng. Ví dụ: >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) >>> # Find the ten most common words in Hamlet >>> import re >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]Lớp ________ 60 ________ 89 ([itsable-or aper]) ¶([iterable-or-mapping])¶ A class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1 là một lớp con c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 để đếm các đối tượng băm. Đó là một bộ sưu tập trong đó các yếu tố được lưu trữ dưới dạng các khóa từ điển và số lượng của chúng được lưu trữ dưới dạng giá trị từ điển. Số lượng được phép là bất kỳ giá trị số nguyên nào bao gồm số không hoặc số âm. Lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1 tương tự như túi hoặc multiset trong các ngôn ngữ khác. Các yếu tố được tính từ một điều không thể đi được hoặc khởi tạo từ một ánh xạ khác (hoặc bộ đếm): >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args Các đối tượng bộ đếm có giao diện từ điển ngoại trừ việc chúng trả lại số không cho các mục bị thiếu thay vì tăng >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry3: >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 0 Đặt số đếm thành 0 không loại bỏ một phần tử khỏi bộ đếm. Sử dụng >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry4 để loại bỏ nó hoàn toàn: >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry Mới trong phiên bản 3.1. Đã thay đổi trong phiên bản 3.7: Là một lớp con c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 subclass, class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1 inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand. Đối tượng Counter hỗ trợ các phương thức bổ sung ngoài các phương thức có sẵn cho tất cả các từ điển: Trả về một trình lặp qua các phần tử lặp lại mỗi lần nhiều lần. Các yếu tố được trả lại theo thứ tự lần đầu tiên gặp phải. Nếu số lượng phần tử nhỏ hơn một, >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry8 sẽ bỏ qua nó. >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']0 ________ 99 ([n])([n])¶ Trả về một danh sách các yếu tố phổ biến nhất và số lượng của chúng từ số phổ biến nhất đến ít nhất. Nếu N bị bỏ qua hoặc >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']01 trả về tất cả các phần tử trong bộ đếm. Các yếu tố có số lượng bằng nhau được đặt hàng theo thứ tự lần đầu tiên gặp phải: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']1 A([iterable-or-mapping])¶ Các yếu tố được trừ đi từ một bản đồ khác hoặc từ ánh xạ khác (hoặc bộ đếm). Giống như >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args9 nhưng trừ đi thay vì thay thế chúng. Cả đầu vào và đầu ra có thể bằng không hoặc âm. >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']2 Mới trong phiên bản 3.2. ________ 104 ()()¶Tính tổng số của số đếm. >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']3 Mới trong phiên bản 3.10. Các phương thức từ điển thông thường có sẵn cho các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1 ngoại trừ hai đối tượng hoạt động khác nhau cho các bộ đếm. ________ 106 (có thể lặp lại) ¶(iterable)¶ Phương pháp lớp này không được triển khai cho các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1. A([iterable-or-mapping])¶ Các yếu tố được tính từ một sự lặp lại hoặc thêm vào từ một ánh xạ khác (hoặc bộ đếm). Giống như >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args9 nhưng thêm số lượng thay vì thay thế chúng. Ngoài ra, điều đó được dự kiến sẽ là một chuỗi các yếu tố, không phải là một chuỗi các cặp >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']10. Các bộ đếm hỗ trợ các nhà khai thác so sánh phong phú cho các mối quan hệ bình đẳng, tập hợp con và superset: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']11, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']12, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']13, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']14, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']15, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']16. Tất cả các thử nghiệm đó đều coi các yếu tố bị thiếu là không có số lượng nào để >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']17 trả về đúng. Mới trong phiên bản 3.10: Các hoạt động so sánh phong phú đã được thêm vào.Rich comparison operations were added. Thay đổi trong phiên bản 3.10: Trong các bài kiểm tra bình đẳng, các yếu tố bị thiếu được coi là không có số lượng. Trước đây, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']18 and >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']19 were considered distinct. Các mẫu phổ biến để làm việc với các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']4 Một số hoạt động toán học được cung cấp để kết hợp các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})1 để tạo ra multiset (các quầy có số lượng lớn hơn 0). Ngoài ra và trừ các bộ đếm kết hợp bằng cách thêm hoặc trừ đi số lượng của các yếu tố tương ứng. Giao lộ và liên minh trả lại mức tối thiểu và tối đa của số lượng tương ứng. Bình đẳng và bao gồm so sánh số lượng tương ứng. Mỗi thao tác có thể chấp nhận đầu vào với số lượng đã ký, nhưng đầu ra sẽ loại trừ kết quả với số lượng 0 hoặc ít hơn. >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']5 Bổ sung và trừ không phải là các phím tắt để thêm một bộ đếm trống hoặc trừ từ một bộ đếm trống. >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']6 Mới trong phiên bản 3.3: Đã thêm hỗ trợ cho Unary Plus, Minus Minus và các hoạt động Multiset tại chỗ.Added support for unary plus, unary minus, and in-place multiset operations. Ghi chú Bộ đếm được thiết kế chủ yếu để hoạt động với các số nguyên dương để thể hiện số lượng chạy; Tuy nhiên, sự chăm sóc đã được thực hiện để không ngăn chặn các trường hợp sử dụng không cần thiết cần các loại hoặc giá trị âm khác. Để giúp với các trường hợp sử dụng đó, phần này ghi lại phạm vi tối thiểu và các hạn chế loại.
Xem thêm
c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary 9 Đối tượngLớp ________ 60 ________ 131 ([Itable [, Maxlen]])([iterable[, maxlen]])¶Trả về một đối tượng Deque mới được khởi tạo từ trái sang phải (sử dụng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']32) với dữ liệu từ ITable. Nếu có thể được chỉ định, Deque mới trống. Deques là một khái quát của các ngăn xếp và hàng đợi (cái tên được phát âm là bộ bài và viết tắt của hàng đợi hai kết thúc). Deques hỗ trợ chủ đề an toàn, bộ nhớ hiệu quả và bật lên từ hai bên của deque với hiệu suất x x xấp xỉ cùng một trong hai hướng. Mặc dù các đối tượng c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5 hỗ trợ các hoạt động tương tự, chúng được tối ưu hóa cho các hoạt động có độ dài cố định nhanh và chi phí chuyển động bộ nhớ O (N) cho các hoạt động >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']34 và >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']35 thay đổi cả kích thước và vị trí của biểu diễn dữ liệu cơ bản. Nếu maxlen không được chỉ định hoặc là >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00, các deques có thể phát triển đến một độ dài tùy ý. Mặt khác, deque được giới hạn với chiều dài tối đa được chỉ định. Khi một deque có độ dài giới hạn là đầy đủ, khi các mục mới được thêm vào, một số lượng vật phẩm tương ứng được loại bỏ từ đầu đối diện. Các deques có độ dài giới hạn cung cấp chức năng tương tự như bộ lọc >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']37 trong Unix. Chúng cũng hữu ích cho việc theo dõi các giao dịch và các nhóm dữ liệu khác trong đó chỉ có hoạt động gần đây nhất được quan tâm. Các đối tượng Deque hỗ trợ các phương pháp sau: ________ 138 (x)(x)¶Thêm X vào phía bên phải của deque. ________ 139 (x)(x)¶Thêm x vào phía bên trái của deque. ________ 140 ()()¶Hủy bỏ tất cả các phần tử từ deque để lại nó với chiều dài 0. ________ 141 ()()¶Tạo một bản sao nông của deque. Mới trong phiên bản 3.5. ________ 142 (x)(x)¶Đếm số lượng các phần tử deque bằng x. Mới trong phiên bản 3.2. ________ 143 (có thể lặp lại) ¶(iterable)¶Mở rộng phía bên phải của deque bằng cách nối thêm các yếu tố từ đối số có thể lặp lại. ________ 144 (có thể lặp lại) ¶(iterable)¶Mở rộng phía bên trái của deque bằng cách nối thêm các yếu tố từ Itable. Lưu ý, một loạt các ứng dụng bên trái dẫn đến việc đảo ngược thứ tự của các phần tử trong đối số có thể lặp lại. ________ 145 (x [, bắt đầu [, dừng]])(x[, start[, stop]])¶Trả về vị trí của X trong deque (tại hoặc sau khi chỉ mục bắt đầu và trước khi dừng chỉ mục). Trả về trận đấu đầu tiên hoặc tăng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']46 nếu không tìm thấy. Mới trong phiên bản 3.5. ________ 142 (x)(i, x)¶Đếm số lượng các phần tử deque bằng x. Mới trong phiên bản 3.2. Mới trong phiên bản 3.5. ________ 142 (x)()¶Đếm số lượng các phần tử deque bằng x. Mới trong phiên bản 3.2.()¶________ 143 (có thể lặp lại) ¶ Mở rộng phía bên phải của deque bằng cách nối thêm các yếu tố từ đối số có thể lặp lại.(value)¶________ 144 (có thể lặp lại) ¶ Mở rộng phía bên trái của deque bằng cách nối thêm các yếu tố từ Itable. Lưu ý, một loạt các ứng dụng bên trái dẫn đến việc đảo ngược thứ tự của các phần tử trong đối số có thể lặp lại.()¶________ 145 (x [, bắt đầu [, dừng]]) Mới trong phiên bản 3.2. ________ 143 (có thể lặp lại) ¶(n=1)¶Mở rộng phía bên phải của deque bằng cách nối thêm các yếu tố từ đối số có thể lặp lại. ________ 144 (có thể lặp lại) ¶ Mở rộng phía bên trái của deque bằng cách nối thêm các yếu tố từ Itable. Lưu ý, một loạt các ứng dụng bên trái dẫn đến việc đảo ngược thứ tự của các phần tử trong đối số có thể lặp lại. ________ 145 (x [, bắt đầu [, dừng]])Trả về vị trí của X trong deque (tại hoặc sau khi chỉ mục bắt đầu và trước khi dừng chỉ mục). Trả về trận đấu đầu tiên hoặc tăng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']46 nếu không tìm thấy. ________ 147 (i, x) Chèn x vào deque ở vị trí i. Bắt đầu từ phiên bản 3.5, hỗ trợ Deques >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']68, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']69 và >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']70. Example: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']8 c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary 9 Bí quyếtPhần này cho thấy các cách tiếp cận khác nhau để làm việc với Deques. Các deques có độ dài giới hạn cung cấp chức năng tương tự như bộ lọc >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']37 trong Unix: >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']9 Một cách tiếp cận khác để sử dụng Deques là duy trì một chuỗi các yếu tố được thêm gần đây bằng cách nối vào bên phải và bật bên trái: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))0 Một bộ lập lịch vòng tròn có thể được triển khai với các trình lặp đầu vào được lưu trữ trong một c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary9. Các giá trị được mang lại từ trình lặp hoạt động ở vị trí 0. Nếu máy lặp đó cạn kiệt, nó có thể được loại bỏ với >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']74; Nếu không, nó có thể được đạp trở lại cuối cùng với phương pháp >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']75: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))1 Phương pháp >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']75 cung cấp một cách để thực hiện cắt và xóa c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary9. Ví dụ, việc triển khai Python thuần túy của >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']78 dựa trên phương thức >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']75 để các yếu tố định vị được bật ra: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))2 Để thực hiện cắt c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary9, hãy sử dụng một cách tiếp cận tương tự áp dụng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']75 để đưa phần tử mục tiêu vào phía bên trái của deque. Xóa các mục cũ bằng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']74, thêm các mục mới với >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']83, sau đó đảo ngược vòng quay. Với các biến thể nhỏ trên phương pháp đó, thật dễ dàng để thực hiện các thao tác ngăn xếp kiểu như >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']84, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']85, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']86, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']87, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']88, >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']89 và >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']90. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 3 Đối tượngLớp ________ 60 ________ 193 (default_factory = none, /[, ...]) ¶(default_factory=None, /[, ...])¶Trả về một đối tượng giống như từ điển mới. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})3 là một lớp con của lớp c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 tích hợp. Nó ghi đè một phương thức và thêm một biến thể hiện có thể ghi. Chức năng còn lại giống như đối với lớp c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 và không được ghi lại ở đây. Đối số đầu tiên cung cấp giá trị ban đầu cho thuộc tính >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97; Nó mặc định là >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00. Tất cả các đối số còn lại được đối xử giống như khi chúng được chuyển cho hàm tạo c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4, bao gồm các đối số từ khóa. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})3 Các đối tượng hỗ trợ phương pháp sau ngoài các hoạt động c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 tiêu chuẩn: ________ 202 (khóa)(key)¶ Nếu thuộc tính >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 là >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00, thì điều này sẽ tăng ngoại lệ >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry3 với khóa làm đối số. Nếu >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 không phải là >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00, nó được gọi mà không có đối số để cung cấp giá trị mặc định cho khóa đã cho, giá trị này được chèn vào từ điển cho khóa và được trả về. Nếu gọi >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 sẽ đặt ra một ngoại lệ, ngoại lệ này sẽ không thay đổi. Phương pháp này được gọi bằng phương pháp import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))09 của lớp c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 khi không tìm thấy khóa được yêu cầu; Bất cứ điều gì nó trả lại hoặc tăng sau đó được trả lại hoặc tăng lên bởi import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))09. Lưu ý rằng import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))12 không được gọi cho bất kỳ hoạt động nào ngoài import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))09. Điều này có nghĩa là import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))14 sẽ, như từ điển bình thường, trả về >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00 dưới dạng mặc định thay vì sử dụng >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})3 Đối tượng hỗ trợ biến thể hiện sau: ________ 218¶ Thuộc tính này được sử dụng bởi phương pháp import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))12; Nó được khởi tạo từ đối số đầu tiên đến hàm tạo, nếu có hoặc đến >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00, nếu vắng mặt. Đã thay đổi trong phiên bản 3.9: Các toán tử Merge ( >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 00) and update ( >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 01) operators, specified in PEP 584. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 3 Ví dụ JoSử dụng c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5 làm >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97, thật dễ dàng để nhóm một chuỗi các cặp giá trị khóa thành một từ điển danh sách: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))3 Khi mỗi khóa lần đầu tiên gặp phải, nó chưa có trong ánh xạ; Vì vậy, một mục được tự động được tạo bằng hàm >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 trả về một c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5 trống. Hoạt động import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))28 sau đó gắn giá trị vào danh sách mới. Khi các phím gặp lại, việc tra cứu tiến hành bình thường (trả lại danh sách cho khóa đó) và hoạt động import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))28 sẽ thêm một giá trị khác vào danh sách. Kỹ thuật này đơn giản và nhanh hơn một kỹ thuật tương đương bằng cách sử dụng import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))30: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))4 Đặt >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 thành import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))32 làm cho class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})3 hữu ích cho việc đếm (như túi hoặc multiset trong các ngôn ngữ khác): import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))5 Khi một chữ cái lần đầu tiên gặp phải, nó bị thiếu trong ánh xạ, vì vậy hàm >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 gọi import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))35 để cung cấp số lượng mặc định là 0. Hoạt động gia tăng sau đó xây dựng số lượng cho mỗi chữ cái. Hàm import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))35 luôn trả về 0 chỉ là một trường hợp đặc biệt của các hàm không đổi. Một cách nhanh hơn và linh hoạt hơn để tạo các hàm không đổi là sử dụng hàm Lambda có thể cung cấp bất kỳ giá trị không đổi nào (không chỉ bằng không): import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))6 Đặt >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']97 thành c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary6 làm cho class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})3 hữu ích để xây dựng một từ điển của các bộ: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))7 c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary 8 Chức năng nhà máy cho các bộ dữ liệu có các trường được đặt tênCác bộ dữ liệu được đặt tên gán ý nghĩa cho từng vị trí trong một tuple và cho phép mã tự tài liệu dễ đọc hơn. Chúng có thể được sử dụng bất cứ nơi nào sử dụng các bộ dữ liệu thông thường và chúng thêm khả năng truy cập các trường theo tên thay vì chỉ mục vị trí. ________ 60 ________ 242 (typename, field_names, *, rename = false, mặc định = không, mô -đun = không)(typename, field_names, *, rename=False, defaults=None, module=None)¶Trả về một lớp con Tuple mới có tên typename. Lớp con mới được sử dụng để tạo các đối tượng giống như tple có các trường có thể truy cập bằng cách tra cứu thuộc tính cũng như có thể lập chỉ mục và có thể điều chỉnh được. Các trường hợp của lớp con cũng có một tài liệu hữu ích (với tên typename và field_names) và phương thức import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))43 hữu ích liệt kê các nội dung tuple ở định dạng import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))44. Field_names là một chuỗi các chuỗi như import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))45. Ngoài ra, field_names có thể là một chuỗi duy nhất với mỗi tên trường được phân tách bằng khoảng trắng và/hoặc dấu phẩy, ví dụ import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))46 hoặc import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))47. Bất kỳ định danh python hợp lệ nào cũng có thể được sử dụng cho một trường trường ngoại trừ các tên bắt đầu bằng dấu gạch dưới. Định danh hợp lệ bao gồm các chữ cái, chữ số và nhấn mạnh nhưng không bắt đầu bằng một chữ số hoặc dấu gạch dưới và không thể là một import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))48 như lớp, cho, trả lại, toàn cầu, vượt qua hoặc nâng cao. Nếu đổi tên là đúng, tên trường không hợp lệ được tự động thay thế bằng tên vị trí. Ví dụ: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))49 được chuyển đổi thành import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))50, loại bỏ từ khóa import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))51 và tên trường sao chép import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))52. Mặc định có thể là >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera']00 hoặc có thể lặp lại các giá trị mặc định. Vì các trường có giá trị mặc định phải đến sau bất kỳ trường nào mà không có mặc định, nên mặc định được áp dụng cho các tham số ngoài cùng bên phải. Ví dụ: nếu các tên trường là import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))54 và mặc định là import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))55, thì import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))56 sẽ là một đối số bắt buộc, import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))57 sẽ mặc định là import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))58 và import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))59 sẽ mặc định là import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))60.iterable of default values. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))54 and the defaults are import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))55, then import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))56 will be a required argument, import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))57 will default to import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))58, and import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))59 will default to import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))60. Nếu mô -đun được xác định, thuộc tính import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))61 của tple có tên được đặt thành giá trị đó. Các phiên bản tuple không có từ điển mỗi trường hợp, vì vậy chúng rất nhẹ và không yêu cầu nhiều bộ nhớ hơn các bộ đếm thông thường. Để hỗ trợ Pickling, lớp tuple được đặt tên nên được gán cho một biến khớp với tên typename. Đã thay đổi trong phiên bản 3.1: Đã thêm hỗ trợ cho Đổi tên.Added support for rename. Đã thay đổi trong phiên bản 3.6: Đã thêm tham số mô -đun.Added the module parameter. Đã thay đổi trong phiên bản 3.7: Đã xóa tham số dài dòng và thuộc tính import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))62 attribute. Đã thay đổi trong phiên bản 3.7: Đã thêm tham số mặc định và thuộc tính import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))63 attribute. import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))8 Các bộ dữ liệu được đặt tên đặc biệt hữu ích cho việc gán tên trường cho các bộ dữ liệu được trả về bởi các mô -đun import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))64 hoặc import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))65: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))9 Ngoài các phương thức được kế thừa từ các bộ dữ liệu, được đặt tên là các bộ dữ liệu hỗ trợ ba phương thức bổ sung và hai thuộc tính. Để ngăn chặn xung đột với tên trường, tên phương thức và thuộc tính bắt đầu bằng dấu gạch dưới. ClassMethod ________ 266 ________ 267 (Itable) ¶(iterable)¶Phương pháp lớp tạo ra một thể hiện mới từ một chuỗi hiện có hoặc có thể lặp lại. import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])0 ________ 266 ________ 269 ()()¶ Trả về một c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 mới ánh xạ tên trường vào các giá trị tương ứng của chúng: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])1 Đã thay đổi trong phiên bản 3.1: Trả về class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 instead of a regular c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4. Đã thay đổi trong phiên bản 3.8: Trả về c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 instead of an class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2. As of Python 3.7, regular dicts are guaranteed to be ordered. If the extra features of class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 are required, the suggested remediation is to cast the result to the desired type: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))76. ________ 266 ________ 278 (** kwargs) ¶(**kwargs)¶ Trả về một thể hiện mới của bộ tuple được đặt tên thay thế các trường được chỉ định bằng các giá trị mới: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])2 ________ 266 ________ 280¶ Tuple của chuỗi liệt kê các tên trường. Hữu ích cho nội tâm và để tạo các loại tuple mới được đặt tên từ các bộ dữ liệu có tên hiện có. import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])3 ________ 266 ________ 282¶ Tên trường ánh xạ từ điển đến các giá trị mặc định. import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])4 Để truy xuất một trường có tên được lưu trong một chuỗi, hãy sử dụng hàm import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))83: Để chuyển đổi một từ điển thành một tuple có tên, hãy sử dụng trình vận hành sao kép (như được mô tả trong danh sách đối số giải nén):Unpacking Argument Lists): import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])5 Vì một tuple có tên là một lớp Python thông thường, nên rất dễ dàng để thêm hoặc thay đổi chức năng với một lớp con. Dưới đây là cách thêm trường tính toán và định dạng in chiều rộng cố định: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])6 Các lớp con hiển thị ở trên các bộ import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))84 thành một bộ gốc trống. Điều này giúp giữ các yêu cầu bộ nhớ thấp bằng cách ngăn chặn việc tạo từ điển thể hiện. Phân lớp không hữu ích để thêm các trường mới, được lưu trữ. Thay vào đó, chỉ cần tạo một loại tuple có tên mới từ thuộc tính import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))85: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])7 Docstrings có thể được tùy chỉnh bằng cách thực hiện các bài tập trực tiếp cho các trường import builtins pylookup = ChainMap(locals(), globals(), vars(builtins))86: import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])8 Thay đổi trong phiên bản 3.5: Tài liệu tài sản trở nên có thể ghi được.Property docstrings became writeable. Xem thêm
class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 2 Đối tượngTừ điển được đặt hàng giống như từ điển thông thường nhưng có một số khả năng bổ sung liên quan đến các hoạt động đặt hàng. Bây giờ họ đã trở nên ít quan trọng hơn khi lớp c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 tích hợp đạt được khả năng ghi nhớ thứ tự chèn (hành vi mới này đã được đảm bảo trong Python 3.7). Một số khác biệt từ c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 vẫn còn:
Trả về một thể hiện của một lớp con c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4 có các phương thức chuyên về sắp xếp lại thứ tự từ điển. Mới trong phiên bản 3.1. ________ 321 (cuối cùng = true) ¶(last=True)¶Phương thức import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])01 cho từ điển được đặt hàng trả về và xóa một cặp (khóa, giá trị). Các cặp được trả lại theo thứ tự LIFO nếu cuối cùng là đúng hoặc thứ tự FIFO nếu sai. ________ 323 (khóa, cuối cùng = true) ¶(key, last=True)¶ Di chuyển một khóa hiện có đến một trong hai đầu của một từ điển được đặt hàng. Mục được di chuyển sang đầu bên phải nếu cuối cùng là đúng (mặc định) hoặc đến đầu nếu cuối cùng là sai. Tăng >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry3 nếu khóa không tồn tại: c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary0 Mới trong phiên bản 3.2. Ngoài các phương pháp ánh xạ thông thường, từ điển được đặt hàng cũng hỗ trợ lặp lại bằng cách sử dụng import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])25. Các thử nghiệm bình đẳng giữa các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 có tính nhạy cảm với thứ tự và được thực hiện là import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])27. Các thử nghiệm bình đẳng giữa các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 và các đối tượng import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])29 khác không nhạy cảm với thứ tự như từ điển thông thường. Điều này cho phép các đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 được thay thế bất cứ nơi nào một từ điển thông thường được sử dụng. Đã thay đổi trong phiên bản 3.5: Các mục, khóa và giá trị chế độ xem của class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 now support reverse iteration using import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])25. Đã thay đổi trong phiên bản 3.6: Với sự chấp nhận của PEP 468, thứ tự được giữ lại cho các đối số từ khóa được chuyển cho hàm tạo class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 constructor and its class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})9 method. Đã thay đổi trong phiên bản 3.9: Các toán tử Merge ( >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 00) and update ( >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 01) operators, specified in PEP 584. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 2 ví dụ và công thức nấu ănThật đơn giản để tạo ra một biến thể từ điển theo thứ tự nhằm ghi nhớ thứ tự các khóa được chèn cuối cùng. Nếu một mục mới ghi đè lên một mục nhập hiện có, vị trí chèn ban đầu sẽ được thay đổi và di chuyển đến cuối: c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary1 Một class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})2 cũng sẽ hữu ích cho việc triển khai các biến thể của import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])39: c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary2 c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary3 class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 4 Đối tượngLớp, class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})4 hoạt động như một trình bao bọc xung quanh các đối tượng từ điển. Sự cần thiết của lớp này đã được thay thế một phần bởi khả năng phân lớp trực tiếp từ c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary4; Tuy nhiên, lớp này có thể dễ dàng hơn để làm việc vì từ điển cơ bản có thể truy cập như một thuộc tính. Lớp ________ 60 ________ 344 ([initialData])([initialdata])¶ Lớp mô phỏng một từ điển. Các nội dung của trường hợp được giữ trong một từ điển thông thường, có thể truy cập thông qua thuộc tính import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])45 của các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})4. Nếu initialData được cung cấp, import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])45 được khởi tạo với nội dung của nó; Lưu ý rằng một tham chiếu đến initialData sẽ không được giữ, cho phép nó được sử dụng cho các mục đích khác. Ngoài việc hỗ trợ các phương thức và hoạt động của ánh xạ, các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})4 cung cấp thuộc tính sau: ________ 349¶ Một từ điển thực được sử dụng để lưu trữ nội dung của lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})4. class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 5 Đối tượngLớp này hoạt động như một trình bao bọc xung quanh các đối tượng danh sách. Đây là một lớp cơ sở hữu ích cho các lớp giống như danh sách của riêng bạn có thể kế thừa từ chúng và ghi đè các phương thức hiện có hoặc thêm các phương thức mới. Theo cách này, người ta có thể thêm các hành vi mới vào danh sách. Sự cần thiết của lớp này đã được thay thế một phần bởi khả năng phân lớp trực tiếp từ c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5; Tuy nhiên, lớp này có thể dễ dàng hơn để làm việc vì danh sách cơ bản có thể truy cập như một thuộc tính. Lớp ________ 60 ________ 35 ([Danh sách]) ¶([list])¶ Lớp mô phỏng một danh sách. Các nội dung của phiên bản được giữ trong một danh sách thông thường, có thể truy cập thông qua thuộc tính import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])45 của các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5. Các nội dung của phiên bản ban đầu được đặt thành một bản sao của danh sách, mặc định vào danh sách trống import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])57. Danh sách có thể là bất kỳ điều gì khác, ví dụ như một danh sách Python thực sự hoặc đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5. Ngoài việc hỗ trợ các phương thức và hoạt động của các chuỗi có thể thay đổi, các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5 cung cấp thuộc tính sau: ________ 349¶ Một từ điển thực được sử dụng để lưu trữ nội dung của lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})4.
class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5 are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source. Lớp này hoạt động như một trình bao bọc xung quanh các đối tượng danh sách. Đây là một lớp cơ sở hữu ích cho các lớp giống như danh sách của riêng bạn có thể kế thừa từ chúng và ghi đè các phương thức hiện có hoặc thêm các phương thức mới. Theo cách này, người ta có thể thêm các hành vi mới vào danh sách. Sự cần thiết của lớp này đã được thay thế một phần bởi khả năng phân lớp trực tiếp từ c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary 5; Tuy nhiên, lớp này có thể dễ dàng hơn để làm việc vì danh sách cơ bản có thể truy cập như một thuộc tính.Lớp ________ 60 ________ 35 ([Danh sách]) ¶ Lớp mô phỏng một danh sách. Các nội dung của phiên bản được giữ trong một danh sách thông thường, có thể truy cập thông qua thuộc tínhimport os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])45 của các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5. Các nội dung của phiên bản ban đầu được đặt thành một bản sao của danh sách, mặc định vào danh sách trống import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])57. Danh sách có thể là bất kỳ điều gì khác, ví dụ như một danh sách Python thực sự hoặc đối tượng class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5.(seq)¶ Ngoài việc hỗ trợ các phương thức và hoạt động của các chuỗi có thể thay đổi, các trường hợp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5 cung cấp thuộc tính sau: Một đối tượng c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary5 thực được sử dụng để lưu trữ nội dung của lớp class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5. ________ 349¶ Các yêu cầu phân lớp: Các lớp con của class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})5 dự kiến sẽ cung cấp một hàm tạo có thể được gọi mà không có đối số hoặc một đối số. Danh sách các hoạt động trả về một trình tự mới cố gắng tạo một thể hiện của lớp thực hiện thực tế. Để làm như vậy, nó giả định rằng hàm tạo có thể được gọi với một tham số duy nhất, đó là một đối tượng chuỗi được sử dụng làm nguồn dữ liệu. Nếu một lớp dẫn xuất không muốn tuân thủ yêu cầu này, tất cả các phương pháp đặc biệt được hỗ trợ bởi lớp này sẽ cần phải được ghi đè; Vui lòng tham khảo các nguồn để biết thông tin về các phương pháp cần được cung cấp trong trường hợp đó.New methods import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])76, import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])77, import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])78, import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])79, import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])80, and import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])81. Những bộ sưu tập nào được sử dụng trong Python?Ngôn ngữ lập trình Python có bốn loại dữ liệu thu thập- danh sách, bộ, bộ và từ điển.list, tuple, sets and dictionary.
Bộ sưu tập có phải là một mô -đun không?Mô-đun này thực hiện các kiểu dữ liệu container chuyên dụng cung cấp các lựa chọn thay thế cho các container tích hợp, dict, danh sách, bộ và tuple tích hợp mục đích chung của Python. .
Tôi nên nhập vào bộ sưu tập gì trong Python?Python - Mô -đun bộ sưu tập.. Ví dụ: Khai báo một tuple có tên.>>> Nhập bộ sưu tập >>> Sinh viên = Bộ sưu tập.Được đặt tên ('Sinh viên', [Tên, Tuổi, Dấu hiệu]) .... Ví dụ: Tạo đối tượng của Tuple được đặt tên.>>> S1 = Sinh viên ("Imran", 21, 98) .... Ví dụ: Truy cập có tên Tuple.>>> S1..... Ví dụ: Truy cập có tên Tuple.>>> S1 [0] 'Imran'. |