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.
Use a nested list comprehension:
A=[1,2,3]
B = [prefix + str(a) for a in A for prefix in 'rt']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With