Monday 15 July 2013

python - Merge 2 lists at every x position -


Say I have two lists in length compared to the other, x = [1,2,3] , 4,5, 6,7,8] and y = [a, b, c] and I want to merge each element into y in every third index so that the resulting list Z appear. Like: z = [1,2, a, 3,4, b, 5, 6, c, 7,8]

What is the best way to go about this What is it in Python? Here is a customized version of the roundrobin recipe that you should do: Itertools import cycle,

> , Ilylich DF Merge (a, b, pos): "Merge ('ABCDEF', [1,2,3], 3) -> AbB1CD2EF3" Iterables = [ IAR (A)] * (POS-1) + [IARAAR (B)) Pending = Lane (ITERBEL) NXTS = Chakra (IART) for ITERABLE exchange in it) while pending: Try: Next Naxalites: () StopIteration Sector addition: pending - = 1 nexts = cycle (islice (nexts, pending))

Example:

  & gt; & Gt; & Gt; List (Merge (Xchange (1, 9), 'ABC', 3) # Note that it works for any movable! [1, 2, 'A', 3, 4, 'B', 5, 6, 'C', 7, 8]   

Or you can use Roundrobin () because it is without any modification:

  & gt; & Gt; & Gt; X = [1,2,3,4,5,6,7,8]> gt; & Gt; & Gt; Y = ['a', 'b', 'c']> gt; & Gt; & Gt; List (RoundBrain (* ([[[[[[[[[[[[[[[[[[2] [or])) [1, 2, 'A', 3, 4, 'B', 5, 6, 'C', 7, 8]   

Or equivalent but slightly more readable version:

  & gt; & Gt; & Gt; Xiter = iter (x)> gt; & Gt; & Gt; List (gobbin (xiter, xiter, y)) [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]   

Here is the original code; Roundabout ('ABC', 'D', 'EF') - & gt; Roundabrubin () Implementation: Eittools import cycle, i.e. round roundabine (* etres) from ; ADEBFC "#Reppi is credited to George Squeakis pending = LAN (IterBables) Nexus = Chakra (it) for it in heerables .next) pending: try: next in nexts: next to quit (stop): StopIteration: Pending - = 1 Nexts = cycle (islice (nexts, pending))

No comments:

Post a Comment