簡體   English   中英

計算字典中大於Python中某個數字的值?

[英]Counting values in a dictionary that are greater than a certain number in Python?

我正在尋找一個函數,該函數可以打印發現分數大於或等於90的次數。

因此,如果字典是:

d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}

輸出應為2

嘗試運行我的代碼時收到以下錯誤:ValueError:int()的無效文字,基數為10:“ Tom”

def overNum():
    d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'}
    count = 0


    for number in d:
        if int(number) in d and int(number) >= 90 in d:
            count += 1

            print(count)

如果用戶輸入:numTimes(),則輸出應為:

2

for number in d:將遍歷字典的鍵而不是值。 您可以使用

for number in d.values():

要么

for name, number in d.items():

如果您還需要名稱。

您可以收集大於或等於90的列表中的項目,然后使用len()

>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> len([v for v in d.values() if int(v) >= 90])
2

或使用sum()對布爾值求和而不建立新列表,如@Primusa在評論中所建議的:

>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> sum(int(i) >= 90 for i in d.values())
2

您需要使用items()遍歷字典中的鍵值對

def overNum():
    d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'}
    count = 0

    for name, number in d.items():
        if int(number) >= 90:
            count += 1
    print(count)

我修復的if語句也存在一些問題。

您可以使用filter

len(list(filter(lambda x: int(x[1]) > 90, d.items())))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM