Formatting strings with numeric sequences to generate a list of strings ordered by the numbers in Python

224 views Asked by At

I want a list of strings that is:

[2000q1, 2000q2, 2000q3, 2000q4,
 2001q1, 2001q2, 2001q3, 2001q4,
 2002q1, 2002q2, 2002q3, 2002q4 ...]

and so on.

I'd like to create the result above in Python by str.format.

The following is what I tried:

import numpy as np
x = list(range(2000, 2003))
x = np.repeat(x, 4)
y = [1,2,3,4] * 3

"{}q{}".format(x,y)
# One string containing all numbers (FAILED)

"{x[i for i in x]}q{y[j for j in y]}".format(**{"x": x, "y": y})
# IndexError (FAILED)

Finally I worked it out by:

result = list()
for i in range(0, len(y)):
    result.append("{}q{}".format(x[i],y[i]))
result

Are there any more elegant solutions which don't need an explicit loop? I am looking for something like this in R:

sprintf("%dq%d", x, y)
2

There are 2 answers

0
Mureinik On BEST ANSWER

You could use a nested list comprehension:

result = ['{}q{}'.format(y, q+1) for y in range(2000, 2003) for q in range(4)]
0
Ajax1234 On

You can use map for a functional, although far uglier solution:

import itertools
final_data = list(itertools.chain(*map(lambda x:map(lambda y:"{}q{}".format(x, y), range(1, 5)), range(2000, 2003))))

Output:

['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3', '2001q4', '2002q1', '2002q2', '2002q3', '2002q4']