numpy 如何使用说明中指定的算法从1D创建2D阵列?

qncylg1j  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(128)

下午好,
我需要根据以下规则从1D创建2D阵列:\

  • 二维数组不能包含

[["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"]...]

  • 数组不应重复,对我来说也是如此

[["A1", "A2"], ["A2", "A1"], ....] \

  • 例如输入数组

A ["A1", "A2", "A3", "A4"]
输出数组
B [['A1' 'A2'] ['A1' 'A3']['A1' 'A4']['A2' 'A1']['A2' 'A3']['A2' 'A4']['A3' 'A1'] ['A3' 'A2'] ['A3' 'A4']['A4' 'A1'] ['A4' 'A2']['A4' 'A3']]
我需要
[['A1' 'A2']['A1' 'A3']['A1' 'A4']['A2' 'A3']['A2' 'A4'] ['A3' 'A4']

import numpy as np
    
    x = ("A1", "A2", "A3", "A4")
    
    arr = []
    for i in range(0, len(x)):
        for j in range(0, len(x)):
            if x[i] != x[j]:
                arr.append((x[i], x[j]))
    
    mylist = np.unique(arr, axis=0)
    print(mylist)

怎么做呢?
先谢谢你。

4ioopgfo

4ioopgfo1#

Python的标准库中有一个函数itertools.combinations可以做到这一点。

from itertools import combinations

print( list(combinations(['A1', 'A2', 'A3', 'A4'], 2)) )
# [('A1', 'A2'), ('A1', 'A3'), ('A1', 'A4'), ('A2', 'A3'), ('A2', 'A4'), ('A3', 'A4')]

您也可以使用巢状循环(Nested Loop)在数组上反覆运算,自行撰写:

def all_pairs(arr):
    for i, x in enumerate(arr):
        for y in arr[i+1:]:
            yield (x, y)

print( list(all_pairs(['A1', 'A2', 'A3', 'A4'])) )
# [('A1', 'A2'), ('A1', 'A3'), ('A1', 'A4'), ('A2', 'A3'), ('A2', 'A4'), ('A3', 'A4')]
pnwntuvh

pnwntuvh2#

您只需要一个简单的if语句来检查元组是否已经存在:

import numpy as np
    
    x = ("A1", "A2", "A3", "A4")
    
    arr = []
    for i in range(0, len(x)):
        for j in range(0, len(x)):
            if x[i] != x[j]:
                if not (x[j], x[i]) in arr: // If the pair already exists, it would be the
                                            //flipped version of it
                    arr.append((x[i], x[j]))
    
    mylist = np.unique(arr, axis=0)
    print(mylist)

相关问题