简体   繁体   English

生成一个列表的列表,其元素来自另一个列表(Python)

[英]Generating a list of lists whose elements come from another list (Python)

How can you generate a list of lists, with varying sizes, whose elements are from another list, say, a = [1,2,3] ?如何生成一个大小不同的列表列表,其元素来自另一个列表,例如a = [1,2,3] Ex: If I choose length of the lists to be 2, then I should get [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] .例如:如果我选择列表的长度为 2,那么我应该得到[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]

What you are looking for is called 'binomial combinations', you can read this answer to learn more about it but this code should work with combinations of 2:您要查找的内容称为“二项式组合”,您可以阅读此答案以了解更多信息,但此代码应与 2 的组合一起使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM