![](/img/trans.png)
[英]Read vertically all the values of all the possible combinations of an unknown number of lists with different sizes in Python
[英]Create all possible combinations of lists of different sizes in numpy
我想創建一個 numpy 數組,其中包含來自不同大小的多個列表的所有可能的項目組合:
a = [1, 2]
b = [3, 4]
c = [5, 6, 7]
d = [8, 9, 10]
在每個組合中,我想要 2 個元素。 我不希望有任何重復,也不希望同一列表中的項目混合在一起。
我可以使用np.array(np.meshgrid(a, b, c, d)).T.reshape(-1,3)
獲得所有此類組合,但我需要對,而不是三胞胎。 執行np.array(np.meshgrid(a, b, c, d)).T.reshape(-1,2)
不起作用,因為它只是切斷了原始數組的一列。
關於如何實現這一目標的任何想法?
所以 Itertools 非常適合這個。 您要做的第一件事是將您的列表合並為一個可迭代的列表(列表列表)。 第一步是獲取列表的所有組合。
from itertools import combinations, product
a = [1, 2]
b = [3, 4]
c = [5, 6, 7]
d = [8, 9, 10]
total = [a,b,c,d]
for item in combinations(total, 2):
print(item)
返回
([1, 2], [3, 4])
([1, 2], [5, 6, 7])
([1, 2], [8, 9, 10])
([3, 4], [5, 6, 7])
([3, 4], [8, 9, 10])
([5, 6, 7], [8, 9, 10])
您可以簡單地遍歷各個列表,如下所示
from itertools import combinations
a = [1, 2]
b = [3, 4]
c = [5, 6, 7]
d = [8, 9, 10]
total = [a,b,c,d]
for item in combinations(total, 2):
for sub_item in item[0]:
for second_sub_item in item[1]:
print(sub_item, second_sub_item)
打印出來是
1 3
1 4
2 3
2 4
1 5
1 6
1 7
2 5
2 6
2 7
1 8
1 9
1 10
2 8
2 9
2 10
3 5
3 6
3 7
4 5
4 6
4 7
3 8
3 9
3 10
4 8
4 9
4 10
5 8
5 9
5 10
6 8
6 9
6 10
7 8
7 9
7 10
類似於 Olvin Roght 的評論,但如果你把你的子列表放在一個列表中,你可以這樣做:
>>>> ls = [[1,2],[3,4],[5,6,7],[8,9,10]]
>>>> [item for cmb in combinations(ls, 2) for item in product(*cmb)]
[(1, 3), (1, 4), (2, 3), (2, 4), (1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (1, 8), (1, 9), (1, 10), (2, 8), (2, 9), (2, 10), (3, 5), (3, 6), (3, 7), (4, 5), (4, 6), (4, 7), (3, 8), (3, 9), (3, 10), (4, 8), (4, 9), (4, 10), (5, 8), (5, 9), (5, 10), (6, 8), (6, 9), (6, 10), (7, 8), (7, 9), (7, 10)]
如果您只想使用 numpy 而不使用 itertools,這是一個替代方案。
def all_combinations(arrays):
"""
:param arrays: tuple of 1D lists.
the functions returns the combinations of all these lists.
:return: np.array of shape (len_out, 2).
np.array of all the possible combinations.
"""
len_array = np.asarray([len(elt) for elt in arrays])
# the length of out is equal to the sum of the products
# of each element of len_array with another element of len_array
len_out = (np.sum(len_array) ** 2 - np.sum(len_array ** 2)) // 2
out, next_i = np.empty((len_out, 2), dtype=int), 0
new_elt = arrays[0]
for elt in arrays[1:]:
out_elt = np.asarray(np.meshgrid(new_elt, elt)).T.reshape(-1, 2)
next_j = next_i + len(out_elt)
out[next_i: next_j] = out_elt
next_i = next_j
new_elt = np.concatenate((new_elt, elt))
return out
例子:
>>> arrays = ([1, 2], [3, 4], [5, 6, 7], [8, 9, 10])
>>> all_combinations(arrays)
[[ 1 3]
[ 1 4]
[ 2 3]
...
...
[ 7 8]
[ 7 9]
[ 7 10]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.