简体   繁体   中英

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] ? 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]] .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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