如何提取列表中字典的'g'键值生成新列表并统计小于10的元素数?
Solution
Given the list of student dictionaries, here's how to extract the 'g' values and count those less than 10:
1. Extract 'g' values into a new list
Use a list comprehension to pull the 'g' key's value from each dictionary:
students = [ {'id': 123, 'name': 'x', 'g': 19}, {'id': 378, 'name': 'y', 'g': 8}, {'id': 934, 'name': 'z', 'g': 10} ] # Generate list of 'g' values g_scores = [student['g'] for student in students] print(g_scores) # Output: [19, 8, 10]
2. Count values less than 10
There are two efficient ways to do this:
- Using list comprehension + len():
count = len([score for score in g_scores if score < 10]) print(count) # Output: 2 - Using sum() with generator expression (avoids creating an intermediate list, more memory-efficient):
count = sum(1 for score in g_scores if score < 10) print(count) # Output: 2
Combined one-liner (skip storing the intermediate list)
If you don't need to keep the g_scores list, you can do it in a single step:
count = sum(1 for student in students if student['g'] < 10) print(count) # Output: 2
内容的提问来源于stack exchange,提问作者yashar farzizadeh
相关产品推荐
相关产品推荐

