![](/img/trans.png)
[英]Some numbers are skipped in counting number of values greater and less than certain values in a list
[英]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():
如果您還需要名稱。
您需要使用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.