繁体   English   中英

计算字典中SPECIFIC / CERTAIN值的数量

[英]Counting the number of SPECIFIC/CERTAIN values in dictionary

我不试图计算字典中的值数

这是我的代码:

def use_favcolors(fav_color):
    count = 0
    for green in fav_color:
        if green == fav_color:
            count += 1
    print count

def main():
    use_favcolors({"John": "green", "Bobby": "blue", "PapaSanta": "yellow"})
main()

为什么打印0? 由于字典中有绿色,所以它不打印1吗?

您需要迭代字典的值。 当前,您无需访问值即可迭代字典中的键。

请注意, for i in fav_color中的for i in fav_color是在Python中迭代键的一种惯用方式。

Python迭代值的方法是使用dict.values

def use_favcolors(fav_color):
    count = 0
    for color in fav_color.values():
        if color == 'green':
            count += 1
    print count

实现逻辑的另一种方法是将sum与生成器表达式一起使用。 这是有效的,因为True == 1 ,因为Boolean是int的子类。

d = {"John": "green", "Bobby": "blue", "PapaSanta": "yellow"}

res = sum(i=='green' for i in d.values())  # 1
def use_favcolors(fav_color):
    count = 0
    for i in fav_color:
         if fav_color[i] == "green":
         count += 1
    print(count)

def main():
    use_favcolors({"John": "green", "Bobby": "blue", "PapaSanta": "yellow"})
main()

您的if语句逻辑没有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM