Python结构,用于存储具有频率的项列表

2024-10-01 02:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了两个小时在谷歌上搜索,找不到答案。希望你能给我一些建议

我正在寻找一个python结构,在那里我可以存储一个项目列表及其出现次数。例如:

{["item1","property1"]:10, 
 ["item2","property2"]:5,
 ["item3","property3"]:5}

然后我可以调用类似popitem()的东西,它将返回例如[“item3”,“property3”],结构将更新为以下内容:

{["item1","property1"]:10, 
 ["item2","property2"]:5,
 ["item3","property3"]:4}

有什么想法吗?谢谢


Tags: 项目答案列表次数结构建议小时item1
2条回答

您需要一个子类dict专门用于计数事件。该子类已存在:^{}

请注意Counter与所有dict一样,要求其键是可散列对象,因此:

  • 你可以有Counter({("item1","property1"):10, ("item2","property2"):5, ("item3","property3"):4})
  • 您不能有Counter({["item1","property1"]:10, ["item2","property2"]:5, ["item3","property3"]:4})

随机选择计数器演示

import collection
import random

l = [('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'), ('item2', 'property2'), ('item2', 'property2'), ('item2', 'property2'), ('item2', 'property2'), ('item2', 'property2'), ('item3', 'property3'), ('item3', 'property3'), ('item3', 'property3'), ('item3', 'property3')]

c = collections.Counter(l)

print(c)
# Counter({('item1', 'property1'): 10, ('item2', 'property2'): 5, ('item3', 'property3'): 4})

for i in range(10):
  item, prop = random.choices(list(c.keys()), weights = list(c.values()), k = 1)[0]
  print(item, prop, end=', ')
  c[(item, prop)] -= 1

# item1 property1, item1 property1, item2 property2,
# item2 property2, item3 property3, item1 property1,
# item1 property1, item3 property3, item1 property1,
# item1 property1,

print(c)
# Counter({('item1', 'property1'): 4, ('item2', 'property2'): 3, ('item3', 'property3'): 2})

随机样本计数器演示

import collections
import random

c = collections.Counter({("item1","property1"):10,   ("item2","property2"):5,  ("item3","property3"):4})

popped = random.sample(list(c.keys()), 10, counts=list(c.values()))
c = c - collections.Counter(popped)

print(popped)
# [('item2', 'property2'), ('item2', 'property2'), ('item3', 'property3'),
#  ('item1', 'property1'), ('item1', 'property1'), ('item1', 'property1'),
#  ('item3', 'property3'), ('item1', 'property1'), ('item1', 'property1'),
#  ('item3', 'property3')]

print(c)
# Counter({('item1', 'property1'): 5, ('item2', 'property2'): 3, ('item3', 'property3'): 1})

在python中,不能使用可变键(如列表)生成dict。您可以改用元组

要使popitem()的行为类似于此,必须将字典包装在对象中并实现自己的函数

class youClass(dict):
    def popitem(self):
        key=next(iter(self.keys())) #get one key, will act similary to pop()
        if self[key]>1:
            self[key]-=1
        else:
            del self[key]
        return key

您可以通过以下方式创建dict:

yourDict = yourClass({("item1","property1"):10, 
 ("item2","property2"):5,
 ("item3","property3"):5})

相关问题 更多 >