[英]Combinations in python with different elements
I'm struggling when calculating different types of combinations. 在计算不同类型的组合时,我很挣扎。
Let's explain with an example, I have this array or it could be a dataframe and I want different combinations of some columns from it. 让我们用一个例子来解释,我有这个数组,也可能是一个数据框,我希望从中得到一些列的不同组合。
As I will then multiply this matrix by the combination to sum the numbers. 然后我将这个矩阵乘以组合来求和。
test = np.array ([[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33],
[10,11,12,21,22,31,32,33]])
The possible combinations for the first three columns are [1,0,0],[0,1,0],[0,0,1], so I need 10 or 11 or 12 Following columns, 21 or 22, therefore, combinations [1,0], [0,1] And the last three columns, 31,3 2, 33, then it will be [1,0,0],[0,1,0],[0,0,1] 前三列的可能组合是[1,0,0],[0,1,0],[0,0,1],因此我需要10或11或12个后续列,因此21或22,组合[1,0],[0,1]和最后三列31,3 2,33,则它将是[1,0,0],[0,1,0],[0,0, 1]
So, I get the possible combination by using this function i found in another question. 因此,我可以使用在另一个问题中发现的此功能来获得可能的组合。
n=3
for i in range(2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
print (list(s))
Which gives me: 这给了我:
['0', '0', '0']
['0', '0', '1']
['0', '1', '0']
['0', '1', '1']
['1', '0', '0']
['1', '0', '1']
['1', '1', '0']
['1', '1', '1']
All possible combinations, including the zeros. 所有可能的组合,包括零。 Although I managed to delete those.
虽然我设法删除了那些。
It calculates more than the combinations I need, and I find myself eliminating too many combinations I do not need. 它比我需要的组合计算的更多,而且我发现自己消除了很多不需要的组合。
When I only need these cases: 当我只需要这些情况时:
[1,0,0, 1,0, 1,0,0]
[0,1,0, 1,0, 1,0,0]
[0,0,1, 1,0, 1,0,0]
[1,0,0, 0,1, 1,0,0]
[0,1,0, 0,1, 1,0,0]
[0,0,1, 0,0, 1,0,0]
etc....
I need to delete many rows which are not relevant on the 8 cases, and delete rows where I find more than three 1's, and select where the 1's are positioned correctly,etc... not efficient at all. 我需要删除许多与8种情况无关的行,并删除发现三个以上1的行,然后选择正确放置1的行,等等……根本没有效率。 I'm a bit lost.
我有点迷路了。
I really don't understand the logic behind the example, but does this solve your problem? 我真的不理解该示例背后的逻辑,但这是否可以解决您的问题?
from itertools import product,permutations
a = set(permutations([0,0,1]))
b = set(permutations([0,1]))
comb = []
for t1,t2,t3 in product(a,b,a):
comb.append([*t1,*t2,*t3])
print(comb)
# [[1, 0, 0, 0, 1, 1, 0, 0],
# [1, 0, 0, 0, 1, 0, 1, 0],
# [1, 0, 0, 0, 1, 0, 0, 1],
# [1, 0, 0, 1, 0, 1, 0, 0],
# [1, 0, 0, 1, 0, 0, 1, 0],
# [1, 0, 0, 1, 0, 0, 0, 1],
# [0, 1, 0, 0, 1, 1, 0, 0],
# [0, 1, 0, 0, 1, 0, 1, 0],
# [0, 1, 0, 0, 1, 0, 0, 1],
# [0, 1, 0, 1, 0, 1, 0, 0],
# [0, 1, 0, 1, 0, 0, 1, 0],
# [0, 1, 0, 1, 0, 0, 0, 1],
# [0, 0, 1, 0, 1, 1, 0, 0],
# [0, 0, 1, 0, 1, 0, 1, 0],
# [0, 0, 1, 0, 1, 0, 0, 1],
# [0, 0, 1, 1, 0, 1, 0, 0],
# [0, 0, 1, 1, 0, 0, 1, 0],
# [0, 0, 1, 1, 0, 0, 0, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.