📜  Python多集

📅  最后修改于: 2022-05-13 01:54:43.384000             🧑  作者: Mango

Python多集

Multiset 包类似于Python集合,但它允许元素多次出现。实现可以基于字典元素(它内部使用字典进行存储)到它们在多重集中的多样性。

Python多重集的特点:

  • 元素的无序集合
  • Hashable 就像在一个集合中一样
  • 它支持与Python set 相同的方法
  • 它支持集合操作,如联合、交集和(对称)

安装:

要安装此模块,请在终端中键入以下命令。

pip install multiset

示例 1:多重集的基本示例

在这里,我们将创建一个新的空 Multiset 对象。

Python3
from multiset import *
 
# print empty multiset
print(Multiset())
 
# print multiset from iterable
print(Multiset('abcde'))
 
# print multiset from mapping
print(Multiset({'a': 4, 'b': 2, 'c': 3, 'd':1}))


Python3
# create set
set1 = {'apple', 'ball', 'apple'}
print("Our set is: ", set1)
 
# combine multiset
mltst = Multiset('bal') + set1
print("New multiset: ",mltst)


Python3
mltst = Multiset('aab')
 
# update multiset
mltst.update('a')
print("New added element: ", mltst)


Python3
print(mltst)
mltst.combine("2")


Python3
new_mltst = mltst.copy()
print("Copied multiset",new_mltst)
print("Original ",mltst)



输出:

{}
{a, b, c, d, e}
{a, a, a, a, b, b, c, c, c, d}

示例 2:与 multiset 和 sets 组合

在这里,我们将给出集合和多重集合的组合。为此,我们将使用带集合的多集合加法(+)操作。

Python3

# create set
set1 = {'apple', 'ball', 'apple'}
print("Our set is: ", set1)
 
# combine multiset
mltst = Multiset('bal') + set1
print("New multiset: ",mltst)


输出:

Our set is:  {'ball', 'apple'}
New multiset:  {b, a, l, ball, apple}

示例 3:更改多重集的值

多重集是可变的,因此我们可以使用 update() 方法更改元素。

Python3

mltst = Multiset('aab')
 
# update multiset
mltst.update('a')
print("New added element: ", mltst)


输出:

New added element:  {a, a, a, b}

示例 4:使用组合将值组合到多重集

我们可以使用 combine() 方法组合元素。

Python3

print(mltst)
mltst.combine("2")


输出:

{b, a, l, apple, ball}
{b, a, l, apple, ball, 2}

示例 5:复制多重集

我们可以使用 copy() 方法组合多重集。

Python3

new_mltst = mltst.copy()
print("Copied multiset",new_mltst)
print("Original ",mltst)


输出:

Copied multiset {b, a, l, apple, ball}
Original  {b, a, l, apple, ball}

Python多集对象:

ObjectReturn
combine(*others) Return the multiset resulting from the addition of the sets.
copy() Return a shallow copy of the multiset.
difference() Return The resulting difference multiset.
distinct_elements()Return the multiplicity for element if it is in the multiset, else default
intersection()Return a new multiset with elements common to the multiset and all others
isdisjoint()Return True if the set has no elements in common with other.
issubset()Return True if this set is a subset of the other.
issuperset()Return True if this multiset is a superset of the other.
union_update()Update the multiset, adding elements from all others using the maximum multiplicity.
update():Update the multiset
remove()Removes an element from the multiset.
pop()The multiplicity for element if it is in the multiset, else default.