简体   繁体   中英

Get possible combinations of a list of elements with length 3 in Python

I have a list[x,y,z] where x,y,z can assume any value from {0,1}. I would like to find all possible combinations like [0,0,0],[1,0,0], [1,1,0],... in Python. I have seen that similar questions have been asked before but their were slightly different than what I'm trying to achieve.

To clarify: I want to find all ordered (by order here I mean the order of elements in a list, not the order in which the possible lists are shown) possible lists of the form [x,y,z] where x,y,z = 0 or 1. So in my objective a list [0,1,0] is not the same as [1,0,0]. Doing this by hand my code should find the following lists:

[0,0,0]
[0,0,1]
[0,1,0]
[1,0,0]
[0,1,1]
[1,1,0]
[1,0,1]
[1,1,1]

I would try:

import itertools

nums = [0,1]

comb = list(itertools.product(nums, repeat=3))
print(comb)

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