如何在dict中计算相同的索引?

2024-10-02 00:41:22 发布

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

这是我的代码示例:

budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 18}
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7}
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18}

marged = [budi, ahmad, ika]

我希望结果显示相同的值或索引,例如:

male : 2

Tags: 代码name示例agegendermalefemaleahmad
2条回答

始终可以使用^{}和条件理解:

num_males = sum(1 for subdict in marged if subdict['Gender'] == 'Male')

它迭代marged中的所有词典(这不应该称为merged吗?)并检查'Gender'是否为'Male'。您还可以通过以下方式检查5岁到10岁之间的人数:

num_age_5_to_10 = sum(1 for subdict in marged if 5 <= subdict["Age"] <= 10)

当然,也可以用布尔条件替换1(因为True等价于1,而False等价于0):

num_males = sum(subdict['Gender'] == 'Male' for subdict in marged)
num_age_5_to_10 = sum(5 <= subdict["Age"] <= 10 for subdict in marged)

我认为你有一份记录清单。 你要做的是统计“性别”是“男性”的记录。你知道吗

您可以通过一个小函数来实现这一点:

budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 18}
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7}
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18}

merged = [budi, ahmad, ika]

def count_items(records, key, value):
    values = [r[key] for r in records if key in r]
    return values.count(value)

示例:

print(count_items(merged, "Gender", "Male"))
# -> 2

print(count_items(merged, "Age", 7))
# -> 1

当然,您可以简化:

males = [r["Gender"] for r in merged].count("Male")

相关问题 更多 >

    热门问题