Reputation: 970
My goal is to create a one liner to produce a following list:
list_100 = ['ch1%.2d' % x for x in range(1,6)]
list_200 = ['ch2%.2d' % x for x in range(1,6)]
final_list = list_100 + list_200
[ch101,ch102,ch103,ch104,ch105, ch201,ch202,ch203,ch204,ch205]
is there some way to do that in one line:
final_list = ['ch%.1d%.2d' % (y for y in range(1,3), x for x in range(1,6)]
Upvotes: 1
Views: 122
Reputation: 2792
Something like this perhaps?
final_list = ['ch{}0{}'.format(x,y) for x in range(1,3) for y in range(1,6)]
To address the comment below, you can simply multiply x
by 10:
final_list = ['ch{}{}'.format(x*10,y) for x in range(1,12) for y in range(1,6)]
Upvotes: 2
Reputation: 21619
You could also use itertools.product
to produce the values.
>>> from itertools import product
>>> ['ch{}{:02}'.format(x, y) for x, y in product(range(1,3), range(1, 6))]
['ch101', 'ch102', 'ch103', 'ch104', 'ch105', 'ch201', 'ch202', 'ch203', 'ch204', 'ch205']
Upvotes: 0
Reputation: 104092
I would do:
final_list=["ch{}{:02d}".format(x,y) for x in (1,2) for y in range(1,6)]
#['ch101', 'ch102', 'ch103', 'ch104', 'ch105',
'ch201', 'ch202', 'ch203', 'ch204', 'ch205']
Or, there is nothing wrong with combining what you have:
final_list=['ch1%.2d' % x for x in range(1,6)]+['ch2%.2d' % x for x in range(1,6)]
Upvotes: 0
Reputation: 363486
You were very close:
>>> ['ch%.1d%.2d' % (y, x) for y in range(1,3) for x in range(1,6)]
['ch101',
'ch102',
'ch103',
'ch104',
'ch105',
'ch201',
'ch202',
'ch203',
'ch204',
'ch205']
Upvotes: 2
Reputation: 8966
This is not valid python:
final_list = ['ch%.1d%.2d' % (y for y in range(1,3), x for x in range(1,6)]
...because of unclosed parenthesis.
You want:
print(['ch{}0{}'.format(i, j) for i in range(1, 3) for j in range(1,6)])
Result:
['ch101', 'ch102', 'ch103', 'ch104', 'ch105', 'ch201', 'ch202', 'ch203', 'ch204', 'ch205']
Upvotes: 1