这是我的代码示例:
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
答案 0 :(得分:0)
您始终可以使用sum
和条件理解:
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)
答案 1 :(得分:0)
我认为你有一份记录清单。 你想要的是统计&#34;性别&#34;是&#34;男&#34;。
你可以用一个小功能来做到这一点:
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")