[英]Counting values in a dictionary that are greater than a certain number in Python?
I'm looking to create a function that prints a count of the number of times a grade is found to be greater than or equal to 90. 我正在寻找一个函数,该函数可以打印发现分数大于或等于90的次数。
So if the dictionary is: 因此,如果字典是:
d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
The output should be 2 输出应为2
I get the following error when trying to run my code: ValueError: invalid literal for int() with base 10: 'Tom' 尝试运行我的代码时收到以下错误: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)
if the user inputs: numTimes() the output should be: 如果用户输入:numTimes(),则输出应为:
2
for number in d:
will iterate through the keys of the dictionary, not values. for number in d:
将遍历字典的键而不是值。 You can use 您可以使用
for number in d.values():
or 要么
for name, number in d.items():
if you also need the names. 如果您还需要名称。
You can collect the items in a list that are greater or equal to 90 then take the len()
: 您可以收集大于或等于90的列表中的项目,然后使用len()
:
>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> len([v for v in d.values() if int(v) >= 90])
2
Or using sum()
to sum booleans without building a new list, as suggested by @Primusa in the comments: 或使用sum()
对布尔值求和而不建立新列表,如@Primusa在评论中所建议的:
>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> sum(int(i) >= 90 for i in d.values())
2
You need to iterate over the key-value pairs in the dict with 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)
Also there are some issues with the if
statement that i fixed. 我修复的if
语句也存在一些问题。
您可以使用filter
:
len(list(filter(lambda x: int(x[1]) > 90, d.items())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.