Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: Cycling through iterables diagonally Date: Fri, 26 Feb 2016 10:59:40 +0100 Organization: None Lines: 32 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de q9X6EAAWvGct7UeJxQMbeAZhqye6AIK2nl7iYNczITNA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.002 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'counting': 0.07; 'logic': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'index': 0.13; 'def': 0.13; 'deque': 0.16; 'deque,': 0.16; 'iteration.': 0.16; 'itertools': 0.16; 'popping': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'wrote:': 0.16; '(in': 0.18; 'header:User-Agent:1': 0.26; 'header:X-Complaints-To:1': 0.26; 'cool': 0.27; 'yield': 0.27; 'appending': 0.29; 'weak': 0.29; 'this?': 0.34; 'lists': 0.34; 'list': 0.34; 'follows:': 0.35; 'item': 0.35; 'but': 0.36; 'list,': 0.36; 'there': 0.36; 'to:addr :python-list': 0.36; 'subject:: ': 0.37; 'say': 0.37; 'received:org': 0.37; 'skip:p 20': 0.38; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'some': 0.40; 'back': 0.62; 'course': 0.62; 'spot': 0.63; 'beat': 0.66; 'hoping': 0.77; 'pablo': 0.84 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd8faa.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21rc2 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:103532 Pablo Lucena wrote: > Say I have a group of 4 lists as follows: > > l1 = ['a1', 'a2', 'a3', 'a4'] > l2 = ['b1', 'b2', 'b3', 'b4'] > l3 = ['c1', 'c2', 'c3', 'c4'] > l4 = ['d1', 'd2', 'd3', 'd4'] > > I would like to cycle through these lists "diagonally" in groups of > len(list) (in this example, each list has 4 items). > Prior to this I was mucking around with index counting while looping, and > popping lists out of a deque, popping an item out of the list, and > appending the list back into the deque during each iteration. > > Is there a better/cleaner way to do this? I was hoping for some cool > itertools logic =) I have a weak spot for the itertools myself, but I think in terms of clarity it is hard to beat the conventional def diagonals(a): N = len(a) for i in range(N): for k in range(N): yield a[k][(k+i)%N] print(list(diagonals([l1, l2, l3, l4]))) Of course that's as uncool as it can get ;)