相关疑难解决方法(0)

字典中有多少项在Python中共享相同的值

有没有办法看到字典中有多少项在Python中共享相同的值?

假设我有一个字典,如:

{"a": 600, "b": 75, "c": 75, "d": 90}
Run Code Online (Sandbox Code Playgroud)

我想得到一个结果字典,如:

{600: 1, 75: 2, 90: 1}
Run Code Online (Sandbox Code Playgroud)

我的第一个天真的尝试是只使用嵌套for循环,然后对于每个值,我将再次迭代字典.有一个更好的方法吗?

python dictionary

5
推荐指数
1
解决办法
7642
查看次数

如何在dict中计算相同的值?

我有一个dict看起来像这样:

"votes": {
    "user1": "yes",
    "user2": "no",
    "user3": "yes",
    "user4": "no",
    "user5": "maybe",
    "user6": "yes"
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是,计算相同的值,以便我知道yes发生了3次,no发生了2次,maybe发生了1次.

我现在做的是:

votes = OrderedDict()
for key, value in vote_dict["votes"].items():
    if value in votes:
        votes[value] += 1
    else:
        votes[value] = 1
Run Code Online (Sandbox Code Playgroud)

它工作正常,但肯定有更好的方法来做到这一点.什么是更pythonic方式来做到这一点?

python counter dictionary

4
推荐指数
1
解决办法
926
查看次数

Python:用O(logN)中的给定值计算字典中的项目数

我想用给定的值计算字典中的项目数(假设字典中的值只是数字),我在网上搜索并找到两种方法,第一种方法:

sum(x == chosen_value for x in d.values())
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用Counter in Collections模块.

但是,我认为这两种方法的运行时间是O(N),N字典中的项目总数在哪里.我想找到一种方法来做到这一点O(logN),有可能吗?

在此先感谢任何帮助和建议!

更新:

感谢您的快速回复!它无法完成O(logN).我可以使用二叉树来存储(键,值)对.

python algorithm

0
推荐指数
1
解决办法
249
查看次数

标签 统计

python ×3

dictionary ×2

algorithm ×1

counter ×1