I have a question about the Python grouping module.

Asked 2 years ago, Updated 2 years ago, 118 views

words = ['abc', 'cab', 'cafe', 'goo', 'face']
from itertools import groupby
a = [list(group) for key,group in groupby(sorted(words,key=sorted),sorted)]
print(a)

I found a module in Python that groups anagram, but I don't understand how it works.

What I'm guessing is that the sorted words are grouped based on the sorted key value, and it makes sense that the grouped words are also sorted I don't understand how you can identify the anagram and group it together.

The site I looked up was https://codeday.me/ko/qa/20190730/1176604.html.

Please explain! ㅜㅜ/

python group-by anagram

2022-09-21 21:34

1 Answers

First, to verify that strings a and b are anagramable, the result of sorting strings alphabetically must be the same. (There may be other algorithms, but it's the best known method.)

For example, if you sort each of "face" and "cafe", that is, sorted("face") -> "acef" and sorted("cafe") -> "acef".

Itertools.groupby is a function of grouping list elements according to a condition. The condition of grouping is given as a second factor, a function. In the example above, the conditions for grouping are given by the sorted function. Groupby takes the sorted values for each element in the given string list and groups the same values and gives the result.

But if you just do groupby (words, sorted), it doesn't work. The list to be grouped must be aligned so that the same groups are continuous. So, it's given as groupby (words, key=sorted), sotred).

sorted (words, key=sorted) also looks complicated, sorting words, which means that the criteria for sorting are sorted values for each element.

And, don't cry when you ask questions. There are so many babies.


2022-09-21 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.