hadesfv
hadesfv

Reputation: 386

python combing three lists to one in specific format

I have three lists which I want to make into one list (including all possible combinations 4 for each country abbreviation ) the string they should be is as the following

query = f'c_code={country}&min_age={age[0]}&max_age={age[1]}&gender={gender}'

i.e each country will have 4 strings, I made the following three for loops to do it but I believe this isn't very pythonic.

country_abb=['ID', 'IR', 'IQ', 'IE', 'IM', 'IL', 'IT', 'CI', 'JM', 'JP', 'JE', 'JO', 'KI', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MK', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'NA', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'MP', 'NO', 'OM', 'PK', 'PW']
genders = ['male','female']
ages_range = [[16,25],[26,50]]
all_queries = []
for country in country_abb:
    for gender in genders:
        for age in ages_range:
            query = f'c_code={country}&min_age={age[0]}&max_age={age[1]}&gender={gender}'
            all_queries.append(query)

Upvotes: 1

Views: 66

Answers (2)

LiuXiMin
LiuXiMin

Reputation: 1265

You can also just use list comprehension:

country_abb=['ID', 'IR', 'IQ', 'IE', 'IM', 'IL', 'IT', 'CI', 'JM', 'JP', 'JE', 'JO', 'KI', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MK', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'NA', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'MP', 'NO', 'OM', 'PK', 'PW']
genders = ['male','female']
ages_range = [[16,25],[26,50]]

all_queries = [
    f"c_code={country}&min_age={age[0]}&max_age={age[1]}&gender={gender}"
    for age in ages_range
    for gender in genders
    for country in country_abb
]

Upvotes: 1

JohanL
JohanL

Reputation: 6891

You could use product from itertools. I don't know if it is that more pythonic, but it is a bit shorter and I find it more readable, but I guess you milage may vary:

from itertools import product

country_abb=['ID', 'IR', 'IQ', 'IE', 'IM', 'IL', 'IT', 'CI', 'JM', 'JP', 'JE', 'JO', 'KI', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MK', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'NA', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'MP', 'NO', 'OM', 'PK', 'PW']
genders = ['male','female']
ages_range = [[16,25],[26,50]]
all_queries = []

for country, gender, age in product(country_abb, genders, ages_range):
    query = f'c_code={country}&min_age={age[0]}&max_age={age[1]}&gender={gender}'
    all_queries.append(query)

product creates a list of list where each elements of the orignal lists are combined, quite similiar to a nested for loops in the original post. You can read more about it in the Python documentation here. (Thanks, @roganjosh, for suggesting adding the link.)

Upvotes: 4

Related Questions