Reputation: 1
I'm trying to create a list of strings where each element looks like "TEMP1996_U". The year (1996 in this case) comes from a list of years and the type (U in this case) comes from a list of strings. I want the list to have every combination of year and type.
To get a list with just year, I know I can do this:
years = range(1990,2000)
type_c = ["U", "R", "K", "B"]
temp_list = map('TEMP{0}'.format, years)
Can I add type_c on to this list in a similar way?
Upvotes: 0
Views: 71
Reputation: 33137
A second way (in addition to Alex Hall's answer) could be the following:
years = range(1990,2000)
type_c = ["U", "R", "K", "B"]
temp_list = []
for i in years:
for j in type_c:
temp_list.append("TEMP%s_%s" % (i,j))
Upvotes: 1
Reputation: 2863
You can use list comprehension for this task:
temp_list = ['TEMP{0}_{1}'.format(y, t) for y in years for t in type_c]
It's quite clear and straightforward. That's where python really shines: Simple stuff done simply!
years = range(1990,2000)
type_c = ["U", "R", "K", "B"]
temp_list = ['TEMP{0}_{1}'.format(y, t) for y in years for t in type_c]
print (temp_list)
Upvotes: 1
Reputation: 36013
from itertools import product, starmap
years = range(1990, 2000)
type_c = ["U", "R", "K", "B"]
temp_list = list(starmap('TEMP{0}_{1}'.format, product(years, type_c)))
print(temp_list)
Output:
['TEMP1990_U', 'TEMP1990_R', 'TEMP1990_K', 'TEMP1990_B', 'TEMP1991_U', 'TEMP1991_R', 'TEMP1991_K', 'TEMP1991_B',
'TEMP1992_U', 'TEMP1992_R', 'TEMP1992_K', 'TEMP1992_B', 'TEMP1993_U', 'TEMP1993_R', 'TEMP1993_K', 'TEMP1993_B',
'TEMP1994_U', 'TEMP1994_R', 'TEMP1994_K', 'TEMP1994_B', 'TEMP1995_U', 'TEMP1995_R', 'TEMP1995_K', 'TEMP1995_B',
'TEMP1996_U', 'TEMP1996_R', 'TEMP1996_K', 'TEMP1996_B', 'TEMP1997_U', 'TEMP1997_R', 'TEMP1997_K', 'TEMP1997_B',
'TEMP1998_U', 'TEMP1998_R', 'TEMP1998_K', 'TEMP1998_B', 'TEMP1999_U', 'TEMP1999_R', 'TEMP1999_K', 'TEMP1999_B']
Upvotes: 4