You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取列表中字典的'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:47:40