首页 > 解决方案 > 生成一个列表的列表,其元素来自另一个列表(Python)

问题描述

你如何生成一个列表列表,具有不同的大小,其元素来自另一个列表,比如说,a = [1,2,3]?例如:如果我选择列表的长度为 2,那么我应该得到[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]].

标签: pythonlist

解决方案


您要查找的内容称为“二项式组合”,您可以阅读此答案以了解更多信息,但此代码应与 2 的组合一起使用:

def algorithm(myList):
    possible = [''.join(combination) for combination in product(myList, repeat= 2)]
    return possible
print(algorithm(myList))

推荐阅读