Python集合模块
Python中的集合模块提供了不同类型的容器。 Container 是一个对象,用于存储不同的对象,并提供一种访问包含的对象并对其进行迭代的方法。一些内置容器是 Tuple、List、Dictionary 等。在本文中,我们将讨论 collections 模块提供的不同容器。
Table of Content:
- Counters
- OrderedDict
- DefaultDict
- ChainMap
- NamedTuple
- DeQue
- UserDict
- UserList
- UserString
计数器
注:相当于其他语言的bag或multiset。
句法:
class collections.Counter([iterable-or-mapping])
初始化计数器对象
可以使用 counter()函数初始化计数器对象,并且可以通过以下方式之一调用此函数:
- 带有一系列项目
- 使用包含键和计数的字典
- 使用关键字参数将字符串名称映射到计数
例子:
Python3
# A Python program to show different
# ways to create Counter
from collections import Counter
# With sequence of items
print(Counter(['B','B','A','B','C','A','B',
'B','A','C']))
# with dictionary
print(Counter({'A':3, 'B':5, 'C':2}))
# with keyword arguments
print(Counter(A=3, B=5, C=2))
Python3
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, value in d.items():
print(key, value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
Python3
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
for key, value in od.items():
print(key, value)
# deleting element
od.pop('a')
# Re-inserting the same
od['a'] = 1
print('\nAfter re-inserting')
for key, value in od.items():
print(key, value)
Python3
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining the dict
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
# Iterate through the list
# for keeping the count
for i in L:
# The default value is 0
# so there is no need to
# enter the key first
d[i] += 1
print(d)
Python3
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining a dict
d = defaultdict(list)
for i in range(5):
d[i].append(i)
print("Dictionary with values as list:")
print(d)
Python3
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
print(c)
Python3
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
# Accessing Values using key name
print(c['a'])
# Accessing values using values()
# method
print(c.values())
# Accessing keys using keys()
# method
print(c.keys())
Python3
# Python code to demonstrate ChainMap and
# new_child()
import collections
# initializing dictionaries
dic1 = { 'a' : 1, 'b' : 2 }
dic2 = { 'b' : 3, 'c' : 4 }
dic3 = { 'f' : 5 }
# initializing ChainMap
chain = collections.ChainMap(dic1, dic2)
# printing chainMap
print ("All the ChainMap contents are : ")
print (chain)
# using new_child() to add new dictionary
chain1 = chain.new_child(dic3)
# printing chainMap
print ("Displaying new ChainMap : ")
print (chain1)
Python3
# Python code to demonstrate namedtuple()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# Access using index
print ("The Student age using index is : ",end ="")
print (S[1])
# Access using name
print ("The Student name using keyname is : ",end ="")
print (S.name)
Python3
# Python code to demonstrate namedtuple() and
# _make(), _asdict()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# initializing iterable
li = ['Manjeet', '19', '411997' ]
# initializing dict
di = { 'name' : "Nikhil", 'age' : 19 , 'DOB' : '1391997' }
# using _make() to return namedtuple()
print ("The namedtuple instance using iterable is : ")
print (Student._make(li))
# using _asdict() to return an OrderedDict()
print ("The OrderedDict instance using namedtuple is : ")
print (S._asdict())
Python3
# Python code to demonstrate deque
from collections import deque
# Declaring deque
queue = deque(['name','age','DOB'])
print(queue)
Python3
# Python code to demonstrate working of
# append(), appendleft()
from collections import deque
# initializing deque
de = deque([1,2,3])
# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)
# printing modified deque
print ("The deque after appending at right is : ")
print (de)
# using appendleft() to insert element at right end
# inserts 6 at the beginning of deque
de.appendleft(6)
# printing modified deque
print ("The deque after appending at left is : ")
print (de)
Python3
# Python code to demonstrate working of
# pop(), and popleft()
from collections import deque
# initializing deque
de = deque([6, 1, 2, 3, 4])
# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()
# printing modified deque
print ("The deque after deleting from right is : ")
print (de)
# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()
# printing modified deque
print ("The deque after deleting from left is : ")
print (de)
Python3
# Python program to demonstrate
# userdict
from collections import UserDict
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
# Function to stop deletion
# from dictionary
def __del__(self):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# dictionary
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop popitem
# from Dictionary
def popitem(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
d = MyDict({'a':1,
'b': 2,
'c': 3})
d.pop(1)
Python3
# Python program to demonstrate
# userlist
from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
# Function to stop deletion
# from List
def remove(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# List
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
# Deleting From List
L.remove()
Python3
# Python program to demonstrate
# userstring
from collections import UserString
# Creating a Mutable String
class Mystring(UserString):
# Function to append to
# string
def append(self, s):
self.data += s
# Function to remove from
# string
def remove(self, s):
self.data = self.data.replace(s, "")
# Driver's code
s1 = Mystring("Geeks")
print("Original String:", s1.data)
# Appending to string
s1.append("s")
print("String After Appending:", s1.data)
# Removing from string
s1.remove("e")
print("String after Removing:", s1.data)
输出:
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
注意:有关更多信息,请参阅Python中的计数器。
有序字典
OrderedDict 也是字典的子类,但与字典不同,它记住插入键的顺序。
句法:
class collections.OrderDict()
例子:
Python3
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, value in d.items():
print(key, value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
输出:
This is a Dict:
a 1
b 2
c 3
d 4
This is an Ordered Dict:
a 1
b 2
c 3
d 4
在删除和重新插入相同的密钥时,会将密钥推到最后,以保持密钥的插入顺序。
例子:
Python3
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
for key, value in od.items():
print(key, value)
# deleting element
od.pop('a')
# Re-inserting the same
od['a'] = 1
print('\nAfter re-inserting')
for key, value in od.items():
print(key, value)
输出:
Before Deleting
a 1
b 2
c 3
d 4
After re-inserting
b 2
c 3
d 4
a 1
注意:有关详细信息,请参阅Python中的 OrderedDict
默认字典
DefaultDict 也是字典的子类。它用于为不存在且从不引发 KeyError 的键提供一些默认值。
句法:
class collections.defaultdict(default_factory)
default_factory 是一个为创建的字典提供默认值的函数。如果此参数不存在,则引发 KeyError。
初始化 DefaultDict 对象
可以使用 DefaultDict() 方法通过将数据类型作为参数传递来初始化 DefaultDict 对象。
例子:
Python3
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining the dict
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
# Iterate through the list
# for keeping the count
for i in L:
# The default value is 0
# so there is no need to
# enter the key first
d[i] += 1
print(d)
输出:
defaultdict(, {1: 2, 2: 3, 3: 1, 4: 2})
示例 2:
Python3
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining a dict
d = defaultdict(list)
for i in range(5):
d[i].append(i)
print("Dictionary with values as list:")
print(d)
输出:
Dictionary with values as list:
defaultdict(
注意:更多信息请参考Python中的 Defaultdict
链图
ChainMap 将许多字典封装到一个单元中并返回字典列表。
句法:
class collections.ChainMap(dict1, dict2)
例子:
Python3
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
print(c)
输出:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
从 ChainMap 访问键和值
可以使用键名访问 ChainMap 中的值。也可以使用 keys() 和 values() 方法访问它们。
例子:
Python3
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
# Accessing Values using key name
print(c['a'])
# Accessing values using values()
# method
print(c.values())
# Accessing keys using keys()
# method
print(c.keys())
输出:
1
ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
添加新词典
可以使用new_child()方法添加新字典。新添加的字典添加在 ChainMap 的开头。
例子:
Python3
# Python code to demonstrate ChainMap and
# new_child()
import collections
# initializing dictionaries
dic1 = { 'a' : 1, 'b' : 2 }
dic2 = { 'b' : 3, 'c' : 4 }
dic3 = { 'f' : 5 }
# initializing ChainMap
chain = collections.ChainMap(dic1, dic2)
# printing chainMap
print ("All the ChainMap contents are : ")
print (chain)
# using new_child() to add new dictionary
chain1 = chain.new_child(dic3)
# printing chainMap
print ("Displaying new ChainMap : ")
print (chain1)
输出:
All the ChainMap contents are :
ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Displaying new ChainMap :
ChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})
注意:更多信息请参考Python中的 ChainMap
命名元组
NamedTuple 返回一个元组对象,其中包含普通元组缺少的每个位置的名称。例如,考虑一个元组名称 student,其中第一个元素表示 fname,第二个表示 lname,第三个元素表示 DOB。假设调用 fname 而不是记住索引位置,您可以使用 fname 参数实际调用元素,那么访问元组元素将非常容易。此功能由 NamedTuple 提供。
句法:
class collections.namedtuple(typename, field_names)
例子:
Python3
# Python code to demonstrate namedtuple()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# Access using index
print ("The Student age using index is : ",end ="")
print (S[1])
# Access using name
print ("The Student name using keyname is : ",end ="")
print (S.name)
输出:
The Student age using index is : 19
The Student name using keyname is : Nandini
转换操作
1. _make():此函数用于从作为参数传递的可迭代对象中返回一个命名元组()。
2._asdict():这个函数返回 从 namedtuple() 的映射值构造的 OrdereDict()。
例子:
Python3
# Python code to demonstrate namedtuple() and
# _make(), _asdict()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# initializing iterable
li = ['Manjeet', '19', '411997' ]
# initializing dict
di = { 'name' : "Nikhil", 'age' : 19 , 'DOB' : '1391997' }
# using _make() to return namedtuple()
print ("The namedtuple instance using iterable is : ")
print (Student._make(li))
# using _asdict() to return an OrderedDict()
print ("The OrderedDict instance using namedtuple is : ")
print (S._asdict())
输出:
The namedtuple instance using iterable is :
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
注意:有关详细信息,请参阅Python中的 NamedTuple
双端队列
Deque(双端队列)是用于从容器两侧更快地追加和弹出操作的优化列表。与具有 O(n) 时间复杂度的列表相比,它为追加和弹出操作提供 O(1) 时间复杂度。
句法:
class collections.deque(list)
此函数将列表作为参数。
例子:
Python3
# Python code to demonstrate deque
from collections import deque
# Declaring deque
queue = deque(['name','age','DOB'])
print(queue)
输出:
deque(['name', 'age', 'DOB'])
插入元素
deque 中的元素可以从两端插入。从右边的 append() 方法插入元素,从左边的 appendleft() 方法插入元素。
例子:
Python3
# Python code to demonstrate working of
# append(), appendleft()
from collections import deque
# initializing deque
de = deque([1,2,3])
# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)
# printing modified deque
print ("The deque after appending at right is : ")
print (de)
# using appendleft() to insert element at right end
# inserts 6 at the beginning of deque
de.appendleft(6)
# printing modified deque
print ("The deque after appending at left is : ")
print (de)
输出:
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
移除元素
也可以从两端从双端队列中删除元素。要从右侧删除元素使用 pop() 方法,从左侧删除元素使用 popleft() 方法。
例子:
Python3
# Python code to demonstrate working of
# pop(), and popleft()
from collections import deque
# initializing deque
de = deque([6, 1, 2, 3, 4])
# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()
# printing modified deque
print ("The deque after deleting from right is : ")
print (de)
# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()
# printing modified deque
print ("The deque after deleting from left is : ")
print (de)
输出:
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
注意:有关详细信息,请参阅Python中的双端队列。
用户字典
UserDict 是一个类似字典的容器,充当字典对象的包装器。当有人想要创建具有某些修改或新功能的自己的字典时,使用此容器。
句法:
class collections.UserDict([initialdata])
例子:
Python3
# Python program to demonstrate
# userdict
from collections import UserDict
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
# Function to stop deletion
# from dictionary
def __del__(self):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# dictionary
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop popitem
# from Dictionary
def popitem(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
d = MyDict({'a':1,
'b': 2,
'c': 3})
d.pop(1)
输出:
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 32, in
d.pop(1)
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 20, in pop
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in:
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 15, in __del__
RuntimeError: Deletion not allowed
注意:更多信息请参考Python中的 UserDict
用户列表
UserList 是一个类似列表的容器,充当列表对象的包装器。当有人想要创建自己的具有一些修改或附加功能的列表时,这很有用。
句法:
class collections.UserList([list])
例子:
Python3
# Python program to demonstrate
# userlist
from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
# Function to stop deletion
# from List
def remove(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# List
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
# Deleting From List
L.remove()
输出:
Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in
L.remove()
File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
注意:更多信息请参考Python中的 UserList
用户字符串
UserString 是一个类似于容器的字符串,就像 UserDict 和 UserList 一样,它充当字符串对象的包装器。当有人想要创建自己的带有一些修改或附加功能的字符串时使用它。
句法:
class collections.UserString(seq)
例子:
Python3
# Python program to demonstrate
# userstring
from collections import UserString
# Creating a Mutable String
class Mystring(UserString):
# Function to append to
# string
def append(self, s):
self.data += s
# Function to remove from
# string
def remove(self, s):
self.data = self.data.replace(s, "")
# Driver's code
s1 = Mystring("Geeks")
print("Original String:", s1.data)
# Appending to string
s1.append("s")
print("String After Appending:", s1.data)
# Removing from string
s1.remove("e")
print("String after Removing:", s1.data)
输出:
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
注意:更多信息请参考Python中的 UserString
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。