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
Post a Comment