Home > Software design >  Preserve ordering of Python's itertools.product
Preserve ordering of Python's itertools.product

Time:04-21

I want to find all the combinations of two lists using itertools's product function:

from itertools import product
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
years = ['2021', '2022']
list(product(*[months, years]))

This outputs

 [('January', '2021'), ('January', '2022'), ('February', '2021'), ('February', '2022'), ('March', '2021'), ('March', '2022'), ('April', '2021'),

and so on. Is it possible to preserve the order of the months list? I also want to convert the tuples to strings where the months and years elements are separated by _.

This is what I'm aiming to get:

['January_2021', 'February_2021', 'March_2021', 'April_2021', ...

CodePudding user response:

Just swap the lists in itertools.product:

out = [f"{m}_{y}" for y, m in product(*[years, months])]
print(out)

Prints:

[
    "January_2021",
    "February_2021",
    "March_2021",
    "April_2021",
    "May_2021",
    "June_2021",
    "July_2021",
    "August_2021",
    "September_2021",
    "October_2021",
    "November_2021",
    "December_2021",
    "January_2022",
    "February_2022",
    "March_2022",
    "April_2022",
    "May_2022",
    "June_2022",
    "July_2022",
    "August_2022",
    "September_2022",
    "October_2022",
    "November_2022",
    "December_2022",
]

CodePudding user response:

Yes, you just need to swap the order of the arguments to product(), and then do a little string manipulation on each tuple that's produced:

list('_'.join([month, year]) for year, month in product(*[years, months]))

This outputs:

['January_2021', 'February_2021', 'March_2021', 'April_2021', 'May_2021', 'June_2021', 'July_2021', 'August_2021', 'September_2021', 'October_2021', 'November_2021', 'December_2021', 'January_2022', 'February_2022', 'March_2022', 'April_2022', 'May_2022', 'June_2022', 'July_2022', 'August_2022', 'September_2022', 'October_2022', 'November_2022', 'December_2022']

CodePudding user response:

You could map str.format:

out = list(map('{0[1]}_{0[0]}'.format, product(*[years, months])))

Output:

['January_2021', 'February_2021', 'March_2021', 'April_2021', 'May_2021', 'June_2021', 
 'July_2021', 'August_2021', 'September_2021', 'October_2021', 'November_2021', 'December_2021', 
 'January_2022', 'February_2022', 'March_2022', 'April_2022', 'May_2022', 'June_2022', 'July_2022', 
 'August_2022', 'September_2022', 'October_2022', 'November_2022', 'December_2022']
  • Related