保留 Python 的 itertools.product 的顺序

Preserve ordering of Python's itertools.product

我想使用 itertools 的乘积函数找到两个列表的所有组合:

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

这输出

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

等等。是否可以保留 months 列表的顺序?我还想将元组转换为字符串,其中 monthsyears 元素由 _.

分隔

这就是我的目标:

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

只需交换 itertools.product 中的列表:

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

打印:

[
    "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",
]

是的,您只需将参数的顺序交换为 product(),然后对生成的每个元组进行一些字符串操作:

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

这输出:

['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']

你可以映射 str.format:

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

输出:

['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']