DEV Community

Cover image for การใช้ itertools.groupby ใน Python
Phondanai
Phondanai

Posted on

1 1

การใช้ itertools.groupby ใน Python

สมมติว่าเรามีข้อมูลชุดหนึ่งที่อยากจัดกลุ่มตามตัวเลขตัวแรกของสมาชิก

data = [
  (10, "ten"),
  (1, "one"),
  (2, "two"),
  (5, "five"),
  (20, "twenty"),
  (3, "three"),
  (1, "one-one"),
  (7, "seven"),
  (2, "two-two"),
  (3, "three-three"),
  (1, "one-one-one"),
  (5, "five-five"),
]
Enter fullscreen mode Exit fullscreen mode

และผลลัพธ์ที่เราต้องการคือ

{1: ['one', 'one-one', 'one-one-one']}
{2: ['two', 'two-two']}
{3: ['three', 'three-three']}
{5: ['five', 'five-five']}
{7: ['seven']}
{10: ['ten']}
{20: ['twenty']}
Enter fullscreen mode Exit fullscreen mode

หากใช้ itertools.groupby ตรงๆ จะได้ผลลัพธ์ดังนี้

from itertools import groupby
from operator import itemgetter
for k, g in groupby(data, key=itemgetter(0)):
  {k: list(map(itemgetter(1), g))}

{10: ['ten']}
{1: ['one']}
{2: ['two']}
{5: ['five']}
{20: ['twenty']}
{3: ['three']}
{1: ['one-one']}
{7: ['seven']}
{2: ['two-two']}
{3: ['three-three']}
{1: ['one-one-one']}
{5: ['five-five']}

Enter fullscreen mode Exit fullscreen mode

จากผลลัพธ์จะพบว่า จะไม่ได้ตรงตามกับที่เราต้องการ วิธีการแก้ไข้คือ เราต้อง sort ข้อมูลก่อนที่จะทำการ groupby

for k, g in groupby(sorted(data), key=itemgetter(0)):
  {k: list(map(itemgetter(1), g))}

{1: ['one', 'one-one', 'one-one-one']}
{2: ['two', 'two-two']}
{3: ['three', 'three-three']}
{5: ['five', 'five-five']}
{7: ['seven']}
{10: ['ten']}
{20: ['twenty']}
Enter fullscreen mode Exit fullscreen mode

ก็จะได้ผลลัพธ์ตามที่เราต้องการแล้ว

REF: https://stackoverflow.com/questions/3440549/how-to-use-itertools-groupby-when-the-key-value-is-in-the-elements-of-the-iterab

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay