Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从numpy数组中选择长度为2的所有集合_Python_Arrays_Numpy_Scipy_Combinatorics - Fatal编程技术网

Python 从numpy数组中选择长度为2的所有集合

Python 从numpy数组中选择长度为2的所有集合,python,arrays,numpy,scipy,combinatorics,Python,Arrays,Numpy,Scipy,Combinatorics,这看起来像是一个罐头numpy或scipy函数…但我找不到它 我有一个元组数组,其中元组包含类的平均值和标准差。我需要第二个数组,其中包含所有元组的唯一组合(因此数组中长度为2的所有子集) 例如: original = [(0.5,0.112),(2.3,0.1),(5,0.7)] 我需要: subsets = [((0.5,0.112),(2.3,0.1)),/ ((0.5,0.112),(5,0.7)),/ ((2.3,0.1),(5,0.7))

这看起来像是一个罐头numpy或scipy函数…但我找不到它

我有一个元组数组,其中元组包含类的平均值和标准差。我需要第二个数组,其中包含所有元组的唯一组合(因此数组中长度为2的所有子集)

例如:

original = [(0.5,0.112),(2.3,0.1),(5,0.7)]
我需要:

subsets = [((0.5,0.112),(2.3,0.1)),/
           ((0.5,0.112),(5,0.7)),/
           ((2.3,0.1),(5,0.7))]
对于任意长度的原始数组

我现在得到的是:

def subsets_length_2(vector):
    subset_vector = []
    for i in vector:
        for j in vector:
            if i != j:
                subset_vector.append((i,j))
    subset_vector = np.asarray(np.unique(subset_vector))
    return subset_vector

您可以使用itertools.compositions:

import itertools
subsets = list(itertools.combinations(original, 2))
print subsets
# [((0.5, 0.112), (2.3, 0.1)), ((0.5, 0.112), (5, 0.7)), ((2.3, 0.1), (5, 0.7))]

您可以使用itertools.compositions:

import itertools
subsets = list(itertools.combinations(original, 2))
print subsets
# [((0.5, 0.112), (2.3, 0.1)), ((0.5, 0.112), (5, 0.7)), ((2.3, 0.1), (5, 0.7))]

您仍然可以使用double for循环,但不必使用内部for循环遍历整个数组

def subsets_length_2(vector):
    subset_vector = []
    n = len(vector)
    for i in range(n-1):
        for j in range(i+1, n):
            subset_vector.append((vector[i],vector[j])) 
    return np.asarray(subset_vector)

您仍然可以使用double for循环,但不必使用内部for循环遍历整个数组

def subsets_length_2(vector):
    subset_vector = []
    n = len(vector)
    for i in range(n-1):
        for j in range(i+1, n):
            subset_vector.append((vector[i],vector[j])) 
    return np.asarray(subset_vector)

这看起来像我在想的。谢谢这看起来和我想的一样。谢谢