[英]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.