Reputation:
years = list(range(2001,2003+1)
months = list(range(1,12+1)
I want to get the list as follows which consist all months and all years:
required = ['1.2001', '2.2001', '3.2001'...'12.2001', ....'1.2002', '2.2002', '3.2002'...'12.2002', '1.2003', '2.2003', '3.2003'...'12.2003']
My wrong code, but intended way of coding is below:
required = [x + '.' + (str(y) for y in years) for x in months]
Looking for simplest way of solving it.
Upvotes: 1
Views: 46
Reputation: 239693
You can generate the range of numbers and convert them to strings at the beginning itself
years = list(map(str, range(2001,2004)))
months = list(map(str, range(1,13)))
Then you can use itertools.product
like this
from itertools import product
print([".".join(item[::-1]) for item in product(years, months)])
# ['1.2001', '2.2001', '3.2001', '4.2001', '5.2001', '6.2001'...
Even simpler, your program can be fixed like this
print([y + '.' + x for x in years for y in months])
Note: I am assuming you are using Python 3.x
Upvotes: 3