簡體   English   中英

如何構造所有可能組合的元組列表

[英]How to construct a list of tuples of all possible combinations

我只是想不出辦法解決我的問題:x是整數。 我想要一個x元組的所有可能組合的列表,其中那些元組的元素的范圍是0到x(不包括x)。

因此,如果x = 3我有3 ^ 3個組合: [(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)]

如果x = 4我將具有4元組的4 ^ 4組合,其中這些元組的元素在{0,1,2,3}中。

這是使用itertools獲得所需內容的正確方法:

list(itertools.product(range(3), repeat=3))

輸出為:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1),
 (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0),
 (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2),
 (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1),
 (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0),
 (2, 2, 1), (2, 2, 2)]

當然,可以使用3以外的其他值來擴大規模。通常:

list(itertools.product(range(x), repeat=x))

將適用於任何x

我認為這只是列表理解:

mylist = [(x,y,z) for x in range(3) for y in range(3) for z in range(3)]

請注意,使用itertools.permutations(range(3))不會生成重復項,而只會生成集合(0,1,2)的排列。 也就是說,您不會得到(1、1、2)等。

好的,不是排列,而是重復排列。
無論如何, itertools.product()正在這樣做:

list(itertools.product([0,1,2],repeats=3))

結果:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]

哦,這是騙子。 但我也找到了它:-)

(旁注: 組合是關於子集的,因此元素的順序對它們無關緊要)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM