简体   繁体   中英

Python list comprehension with multiple loops

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)]

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)]

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']

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']

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)]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM