Home > database >  Can't convert an iterator of tuple to an iterator of strings
Can't convert an iterator of tuple to an iterator of strings

Time:04-03

I'm trying to convert an iterator of tuples to an iterator of strings. I must use itertools, so I'm not allowed to use either for or while.

import itertools
def parlar_lloro(it0):
    it1 = filter(lambda x: len(x)>=5, it0)
    it2 = map(lambda x: x[:len(x)-2], it1)
    it3, it4 = itertools.tee(it2, 2)
    n = len(list(it3))
    itn = itertools.repeat('CROA', n)
    ite = zip(it4, itn)
    return itr

What I get when executing this on Python's Shell is:

>>> [(abc,'CROA'),(def,'CROA'),(ghi,'CROA')]

And I want:

>>> ['abc','CROA','def','CROA','ghi','CROA']

CodePudding user response:

If you're suppose to be using itertools then I suspect what you're expected to use is itertools.chain...

Change your return to be (I'm guessing itr is a typo and you meant ite):

return itertools.chain.from_iterable(ite)

Just for reference, the same thing can be accomplished using a list-comp:

res = [sub for el in ((it[:-2], 'CROA') for it in x if len(it) >= 5) for sub in el]
  • Related