Izip_longest with loop instead of fillvalue

Not sure how to get around this, but from itertools function does the following:

izip_longest('ABCD', 'xy', fillvalue='-') โ†’ Ax By C- D-

I was hoping the iterative library would have something for this:

izip_longest_better('ABCDE', 'xy') โ†’ Ax By Cx Dy Ex

Preferably for an arbitrary number of iterations used to generate millions of combinations. I will write my own, but I decided that I would ask, since I am sure that my own will not be very pythonic.

Amazing, It was a cycle that I have not tried. I could also get something working nested for loops on arrays instead of iterators, but this is much better. What I finally used was one that handled in a similar way to izip "

EDIT: Finished with

  def izip_longest_repeat (* args):
     if args:
         lists = sorted (args, key = len, reverse = True)
         result = list (itertools.izip (* ([lists [0]] + [itertools.cycle (l) for l in lists [1:]]))))
     else:
         result = [()]
     return result
+6
source share
2 answers

Something like that?

 >>> import itertools >>> >>> a = 'ABCDE' >>> b = 'xy' >>> >>> list(itertools.izip_longest(a, b, fillvalue='-')) [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-'), ('E', '-')] >>> list(itertools.izip(a, itertools.cycle(b))) [('A', 'x'), ('B', 'y'), ('C', 'x'), ('D', 'y'), ('E', 'x')] 

etc .. And there is a variant of an arbitrary number of iterations (assuming that you do not want the first argument to change cyclically and that you are really not interested in itertools.product):

 >>> a = 'ABCDE' >>> bs = ['xy', (1,2,3), ['apple']] >>> it = itertools.izip(*([a] + [itertools.cycle(b) for b in bs])) >>> list(it) [('A', 'x', 1, 'apple'), ('B', 'y', 2, 'apple'), ('C', 'x', 3, 'apple'), ('D', 'y', 1, 'apple'), ('E', 'x', 2, 'apple')] 
+13
source

For Python 3, you want to use zip_longest since izip_longest deprecated.

 import itertools list = list(itertools.zip_longest('ABCD', 'xy', fillvalue='-')) print(list) // --> Ax By C- D- 
+1
source

Source: https://habr.com/ru/post/909865/


All Articles