gpt4 book ai didi

python - 计算 python 字典的特定键中值的数量

转载 作者:太空宇宙 更新时间:2023-11-04 09:42:33 25 4
gpt4 key购买 nike

有人可以向我解释一下,和/或指导我以正确的/pythonic 方式做这件事吗?

Python 2.7。

最终,我试图遍历字典 countsD:

countsD = {"aa": None, "bb": None, "cc": None, "dd": None} 

并在相应的字典 d 中进行匹配:

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}

将项目的计数作为值添加到相应的匹配键中,最终创建这个countsD

{"aa": 6, "bb": 3, "cc": 2, "dd": 2}

如果我用上面的方法来做

> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}

> for key in d:

>> print(key)
>> print(len(d[key]))

返回的是这个,这就是我想要的

aa
6
cc
2
dd
2
bb
3

但是,如果某个键的值之一仅包含 1 个值(完全可能),例如(参见“cc”):

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45), "dd": (1, 33)}

然后运行相同的 for 循环,我在“cc”键上得到一个错误:

aa
6
cc
Traceback (most recent call last):
File "<interactive input>", line 3, in <module>
TypeError: object of type 'int' has no len()

然而,如果我让那个“cc”键有一个空值(),那么一切都很好。

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> for key in d:
... print(key)
... print(len(d[key]))
...
aa
6
cc
0
dd
2
bb
3

刚才在输入这篇文章的标题时,我提到了 Count number of values in dictionary for each key一个答案。太棒了,一行!但是同样,对于只有一个值的键,它会失败。这个好:

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
>>> new_countsD
{'aa': 6, 'bb': 3, 'cc': 0, 'dd': 2}

这不是,看键“cc”

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (111), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 1, in <dictcomp>
TypeError: object of type 'int' has no len()

那么,是什么给了??我觉得我错过了一些愚蠢的东西......

感谢您的帮助!

最佳答案

在python中,一个单项元组(称为单例)写成(value,),所以你输入的(111)应该写成(111,) 代替;否则它将被视为 111 的整数。

来自 tuple's documentation :

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

关于python - 计算 python 字典的特定键中值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107992/

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