Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend multiple elements in one line iteration [duplicate]

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.

like image 821
Xiaojian Chen Avatar asked Nov 30 '22 14:11

Xiaojian Chen


2 Answers

Use a nested list comprehension:

A=[1,2,3]

B = [prefix + str(a) for a in A for prefix in 'rt']
like image 111
Dani Mesejo Avatar answered Dec 04 '22 10:12

Dani Mesejo


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']
like image 37
timgeb Avatar answered Dec 04 '22 12:12

timgeb