python - Conditionals and itertools.groupby issue -


i using groupby parse list of words , organize them lists length. example:

from itertools import groupby  words = ['this', 'that', 'them', 'who', 'what', 'where', 'whyfore']  key, group in groupby(sorted(words, key = len), len):     print key, list(group)  3 ['who'] 4 ['this', 'that', 'them', 'what'] 5 ['where'] 7 ['whyfore'] 

getting lengths of lists works well:

for key, group in groupby(sorted(words, key = len), len):     print len(list(group))  1 4 1 1 

the issue if put conditional before beforehand this, result:

for key, group in groupby(sorted(words, key = len), len):     if len(list(group)) > 1:         print list(group) 

output:

[] 

why this?

each group iterable, , turning list exhausts it. cannot turn iterable list twice.

store list new variable:

for key, group in groupby(sorted(words, key = len), len):     grouplist = list(group)     if len(grouplist) > 1:         print grouplist 

now consume iterable once:

>>> key, group in groupby(sorted(words, key = len), len): ...     grouplist = list(group) ...     if len(grouplist) > 1: ...         print grouplist ...  ['this', 'that', 'them', 'what'] 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -