python - 循环嵌套列表字典以计算键的出现次数

标签 python list dictionary counter

我正在学习教程,但找不到适合我解决以下问题的答案: 我有一个嵌套在列表中的字典,想要计算特殊键的出现次数,例如“日期”出现两次:

test = [{'Category': 'a', 'Num': '1', 'Day': 'Tuesday', 'Date': '2013'}, {'Category': 'b', 'Num': '1', 'Day': 'Monday', 'Date': '2013'}]

作为我得到的解决方案:

from collections import Counter
counter = Counter(item["Date"] for item in test)
print counter

这似乎在教程中有效(尽管我仍然没有 100% 理解它),但我想尝试自己编写代码。我想出了各种解决方案,但没有一个有效,我的基础或多或少(只是为了展示我想做的事情,我知道它行不通):

counter = 0
for x in test:
    if x == "Date":
        counter+=1
print counter

最佳答案

有时正确命名变量将有助于我们更好地理解正在解决的问题。

要检查字典中是否存在特定键,可以使用 in 运算符,如下所示

counter = 0
for current_dict in test:
    if "Date" in current_dict:
        counter += 1
print counter

您可以使用列表理解编写相同的逻辑,如下所示

sum([1 for current_dict in test if "Date" in current_dict])

在此代码中,我们使循环和条件平坦,并且要生成的实际值是 1。如果打印此内容

[1 for current_dict in test if "Date" in current_dict]

您将看到与字典列表中出现的 Date 次数一样多的 1。然后使用sum函数我们只是添加整个列表。

这可以进一步缩短。让我们看看如何做到这一点。在Python中, bool 值实际上是整数的子类。所以,在Python中

print True  == 1  # will print True
print False == 0  # will print True

我们可以利用这一点来发挥我们的优势,就像这样

sum(["Date" in current_dict for current_dict in test])

这里我们只是删除了 if 条件,相反,对于列表中的每个字典,我们只是累积一个 bool 值(整数)。 bool 值将为 True (1) 如果 Datecurrent_dict 中,如果不存在,则返回 False (0)。您只需打印即可确认

print ["Date" in current_dict for current_dict in test]

您将得到一系列 0 和 1。我们只需将它们与 sum 相加即可得到结果。

关于python - 循环嵌套列表字典以计算键的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216811/

相关文章:

python - 字典到数据帧错误: "If using all scalar values, you must pass an index"

python - 为什么 time.sleep 提早暂停?

c - 结构链表中的元素编号

Python 在字符 "X"之后的字符串中插入一个换行符

python - 查看字符串列表时什么更快? "In"还是 "index"?

vb.net - 带有两个键的字典条目 - VB.net

javascript - d3 geo - map 投影

python - Pandas 多重索引在 sort_index 方法后未排序

python - 在 Python 中解析、聚合和排序文本文件

python - 向 Python 字典添加重复键 ("Two Sum"问题)