I'd like to transform a list ["A", "B", "C"] to a new list ["A", "A", "B", "B", "C", "C"]. I can think of an ugly loopy way of doing it but is there a one liner?
Asked
Active
Viewed 721 times
3 Answers
2
I would use itertools.repeat
import itertools
n= 2
print([repetition for i in range(10)
for repetition in itertools.repeat(i,n) ])
OUTPUT
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]

Bernardo stearns reisen
- 2,627
- 2
- 7
- 13
-
If you're doing two loops already, you don't need `itertools.repeat`, just use `[i for i in original_input for _ in range(n)]` – Blckknght Apr 03 '20 at 01:36
1
- You can use
itertools.chain
with zip to achieve desired result.
from itertools import chain
l = [1,2,3]
list(chain.from_iterable(zip(l,l)))
Output:
[1,1,2,2,3,3]

Poojan
- 3,366
- 2
- 17
- 33
0
How about list concatenation with itertools?
import itertools
a = ["A", "B", "C"]
c = list(itertools.chain(*[ 2*x for x in a] ))
print(c)
OUTPUT
['A', 'A', 'B', 'B', 'C', 'C']
You could always replace the 2
with a variable.

001001
- 530
- 1
- 4
- 13