1

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)]
1
  • What is wrong with final_list=['ch1%.2d' % x for x in range(1,6)]+['ch2%.2d' % x for x in range(1,6)]? Commented Jul 17, 2018 at 23:12

5 Answers 5

2

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']
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

One concern about this solution is that once the second number goes above 9 it breaks. It is likewise for the other str.format based solution.
You're right, and I noticed that while submitting this, but I took the easy path and just solved what was asked :) - it also wasn't immediately clear to me what the expected behavior would be beyond 9.
1

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

Comments

0

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

2 Comments

In reality, i will have hundreds and thousands of these: row001_column00001 to row001_column00100 to row099_column00001 to row999_column00100
So use range. A nested list comprehension does not have any inherent advantage to the way you are doing it already: two comprehensions and list addition.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.