0

I have

A = ['A','B','C','D','E','F','G','H','J']
B= ['a','b','c']

I want to combine the list that 'a' is combine with first three element of list A , 'b' with the next three and 'c' with the last three as shown below

C = ['Aa','Ba','Ca','Db','Eb','Fb','Gc','Hc','Jc,]

how can I go about it in python

PASCAL MAGONA
  • 107
  • 1
  • 1
  • 7

1 Answers1

6

As a list comprehension you could do this. Although I suspect there's a nicer way to do it.

[f"{capital}{B[i//3]}" for i,capital in enumerate(A)]

i will increment by 1 for each letter in A so we can do floor division by 3 to only increment it every 3 iterations of A giving us the correct index of B and just use an f-string to concaninate the strings although capital + B[i//3] works too.

Jacob
  • 750
  • 5
  • 19
  • Bonus points to explain the solution for the Op? – Captain Caveman May 04 '22 at 20:11
  • @CaptainCaveman I'm trying to think of a more understandable/readable way to do it but if I can't think of one I'll give it a go :) – Jacob May 04 '22 at 20:13
  • 1
    I think what you have is great but it is cryptic to some. – Captain Caveman May 04 '22 at 20:15
  • You can also apply some [`itertools`](https://docs.python.org/3/library/itertools.html) magic which should be significantly faster *(and quite more universal)*: `list(starmap(concat, zip(A, cycle(B))))`. Imports: [`cycle()`](https://docs.python.org/3/library/itertools.html#itertools.cycle), [`starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap), [`concat()`](https://docs.python.org/3/library/operator.html#operator.concat). – Olvin Roght May 04 '22 at 20:15
  • A very ugly `itertools` solution could be: `C = [a+b for a,b in zip(A, chain(*[list(repeat(z,3)) for z in B]))]` – quamrana May 04 '22 at 20:40
  • @quamrana, `chain.from_iterable()`? – Olvin Roght May 04 '22 at 20:43