gpt4 book ai didi

带有重复/重复元素的 Python "set"

转载 作者:IT老高 更新时间:2023-10-28 21:52:03 27 4
gpt4 key购买 nike

是否有一种标准方式来表示可以包含重复元素的“集合”。

据我了解,一个集合恰好有一个元素或零个元素。我希望功能有任何数字。

我目前正在使用以元素为键、数量为值的字典,但这似乎是错误的,原因有很多。

动机:我相信这样的收藏有很多应用。例如,对最喜欢的颜色的调查可以表示为: 调查 = ['蓝色','红色','蓝色','绿色']

在这里,我不关心订单,但我关心数量。我想做这样的事情:

survey.add('blue')
# would give survey == ['blue', 'red', 'blue', 'green', 'blue']

...甚至可能

survey.remove('blue')
# would give survey == ['blue', 'red', 'green']

注意事项:是的,set 不是这种集合的正确术语。还有更正确的吗?

列表当然可以,但所需的集合是无序的。更不用说集合的方法命名在我看来更合适。

最佳答案

您正在寻找 multiset .

Python 最接近的数据类型是 collections.Counter :

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

对于多重集的实际实现,使用 bag pypi 上的数据结构包中的类。请注意,这仅适用于 Python 3。如果您需要 Python 2,here是为 Python 2.4 编写的 bag 的配方。

关于带有重复/重复元素的 Python "set",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10176037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com