在python中生成嵌套元组的所有组合

这是Berkeley Logo中一个简短但完整的程序:

to choices :menu [:sofar []]
if emptyp :menu [print :sofar stop]
foreach first :menu [(choices butfirst :menu sentence :sofar ?)]
end

这就是你如何使用它.你输入

choices [[small medium large]
         [vanilla [ultra chocolate] lychee [rum raisin] ginger]
         [cone cup]]

和Logo回复

    small vanilla cone
    small vanilla cup
    small ultra chocolate cone
    small ultra chocolate cup
    small lychee cone
    small lychee cup
    small rum raisin cone
    small rum raisin cup
    small ginger cone
    small ginger cup
    medium vanilla cone
    medium vanilla cup
    medium ultra chocolate cone
    medium ultra chocolate cup
    medium lychee cone
    medium lychee cup
    medium rum raisin cone
    medium rum raisin cup
    medium ginger cone
    medium ginger cup
    large vanilla cone
    large vanilla cup
    large ultra chocolate cone
    large ultra chocolate cup
    large lychee cone
    large lychee cup
    large rum raisin cone
    large rum raisin cup
    large ginger cone
    large ginger cup

资料来源:http://www.eecs.berkeley.edu/~bh/logo-sample.html

你会如何在python中做到这一点?

最佳答案 像往常一样,
itertools module提供了一个解决方案:

>>> choices = [["small", "medium", "large"],
...            ["vanilla", "ultra chocolate", "lychee", "rum raisin", "ginger"],
...            ["cone", "cup"]]
>>> from itertools import product
>>> print("\n".join(" ".join(item) for item in product(*choices)))
small vanilla cone
small vanilla cup
small ultra chocolate cone
small ultra chocolate cup
small lychee cone
small lychee cup
small rum raisin cone
small rum raisin cup
small ginger cone
small ginger cup
medium vanilla cone
<etc...>
点赞