Extend multiple elements in one line iteration

Viewed 110

For

A=[1,2,3]

I would like to get

B=['r1','t1','r2','t2','r3','t3']

I know it is easy to get ['r1','r2','r3'] by

['r'+str(k) for k in A]

How could I get B by one line loop as I showed above?

Many thanks.

3 Answers

You can use a nested list comprehension.

>>> A=[1,2,3]                                                                                                                            
>>> [fmt.format(n) for n in A for fmt in ('r{}', 't{}')]                                                                                    
['r1', 't1', 'r2', 't2', 'r3', 't3']

Using itertools.product

import itertools
list(itertools.product(*[[1,2,3],['r','t']]))
Out[20]: [(1, 'r'), (1, 't'), (2, 'r'), (2, 't'), (3, 'r'), (3, 't')]
[y +str(x) for x, y in list(itertools.product(*[[1, 2, 3], ['r', 't']]))]
Out[22]: ['r1', 't1', 'r2', 't2', 'r3', 't3']
Related