4

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.

Xiaojian Chen
  • 169
  • 1
  • 7
  • Possible duplicate of https://stackoverflow.com/questions/38400096/how-to-use-list-comprehension-with-extend-list-method, https://stackoverflow.com/questions/5947137/how-can-i-use-a-list-comprehension-to-extend-a-list-in-python, https://stackoverflow.com/questions/44667519/python-how-to-extend-or-append-multiple-elements-in-list-comprehension-format – Andras Deak -- Слава Україні Nov 12 '18 at 15:12

3 Answers3

9

Use a nested list comprehension:

A=[1,2,3]

B = [prefix + str(a) for a in A for prefix in 'rt']
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
6

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']
timgeb
  • 76,762
  • 20
  • 123
  • 145
4

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']
BENY
  • 317,841
  • 20
  • 164
  • 234