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

为何itertools.groupby()无法正常工作?附代码示例求助

Why Your itertools.groupby() Isn't Grouping as Expected

Hey there! Let's break down what's going on with your code. The issue here is a super common gotcha with itertools.groupby(): it only groups consecutive elements that share the same key.

Looking at your student list, entries with the same email domain (like @gmail.com) aren't next to each other—Paul is first, but Gregory comes later after other entries. So groupby() treats each of them as separate groups instead of lumping them together.

What Your Current Code Outputs

Here's what you're probably seeing right now:

@gmail.com
[{'name': 'Paul', 'mail': '@gmail.com'}]
@yahoo.com
[{'name': 'Tom', 'mail': '@yahoo.com'}]
gmail.com
[{'name': 'Jim', 'mail': 'gmail.com'}]
@something.com
[{'name': 'Jules', 'mail': '@something.com'}]
@gmail.com
[{'name': 'Gregory', 'mail': '@gmail.com'}]
@something.com
[{'name': 'Kathrin', 'mail': '@something.com'}]

The Fix: Sort First, Then Group

To get proper grouping, you need to sort the list using the same key you'll use for grouping. This ensures all identical keys are consecutive. Here's the adjusted code:

import itertools

students = [{'name': 'Paul', 'mail': '@gmail.com'}, {'name': 'Tom', 'mail': '@yahoo.com'}, {'name': 'Jim', 'mail': 'gmail.com'}, {'name': 'Jules', 'mail': '@something.com'}, {'name': 'Gregory', 'mail': '@gmail.com'}, {'name': 'Kathrin', 'mail': '@something.com'}]

# Sort the students by their mail field first
sorted_students = sorted(students, key=lambda student: student['mail'])

key_func = lambda student: student['mail']
for key, group in itertools.groupby(sorted_students, key=key_func):
    print(key)
    print(list(group))

What the Fixed Code Outputs

Now you'll get properly grouped results:

gmail.com
[{'name': 'Jim', 'mail': 'gmail.com'}]
@gmail.com
[{'name': 'Paul', 'mail': '@gmail.com'}, {'name': 'Gregory', 'mail': '@gmail.com'}]
@something.com
[{'name': 'Jules', 'mail': '@something.com'}, {'name': 'Kathrin', 'mail': '@something.com'}]
@yahoo.com
[{'name': 'Tom', 'mail': '@yahoo.com'}]

Bonus: Fixing Email Format Inconsistencies

Notice Jim's email is gmail.com (missing the @), so it's grouped separately from @gmail.com. If you want to treat these as the same group, adjust your key function to normalize the email format:

# Strip leading @ from the mail field to group similar domains
key_func = lambda student: student['mail'].lstrip('@')

# Now sort and group with this adjusted key
sorted_students = sorted(students, key=key_func)
for key, group in itertools.groupby(sorted_students, key=key_func):
    print(key)
    print(list(group))

This will group Jim, Paul, and Gregory together under the gmail.com key.

内容的提问来源于stack exchange,提问作者user9441447

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:35:30