重新排列给定矩阵的行,使它们按负对之和的降序排列

Rearrange the rows of the given matrix so that arrange them in descending order of the sum of their negative pairs

任务是在创建的矩阵中重新排列给定矩阵的行,以便 将它们按负对之和的降序排列(正如我在标题中提到的)

这是我尝试过的:

import numpy as np
import random

rows = int(input('\nInput the number of rows: '))
cols = int(input('Input the number of cols: '))


def AutoFill(rows, cols):
    rand_arr = []
    for k in range(rows):
        arr = []
        for v in range(cols):
            a = random.randint(-5, 5)
            arr.append(a)
        rand_arr.append(np.array(arr))
    return np.array(rand_arr)

arr = AutoFill(rows, cols)
PrintArr(arr)


def Rearrange(arr, rows, cols):
    sum = 0
    for i in range(0, rows+1):
        if (arr[i] < 0) and (arr[i] % 2 == 0):
            sum += arr[i]

当我尝试 运行 时出现错误:

    if (arr[i] < 0) and (arr[i] % 2 == 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use 
a.any() or a.all()

非常感谢你的帮助

更新:更大的测试用例:4x4 矩阵

如果我理解这个问题,这段代码应该可以回答您的问题:

import numpy as np
import random

def AutoFill(rows, cols):
    rand_arr = []
    for k in range(rows):
        arr = []
        for v in range(cols):
            a = random.randint(-5, 5)
            arr.append(a)
        rand_arr.append(np.array(arr))
    return np.array(rand_arr)

def reducer(row):
    # Return the value calculated as pwe the "negative pairs" specification
    total = 0
    for i in range(len(row)):
        if i%2 == 0 and row[i] < 0:
            total += row[i]
    return -total  # NOTE the negative sign. It contols the row order.

def Rearrange(arr):
    #  Return the array sorted by the desired "value" of each row.
    return np.array(sorted(arr, key=lambda row: reducer(row)))

#rows = int(input('\nInput the number of rows: '))
#cols = int(input('Input the number of cols: '))

# So that we get repeatable results
random.seed(2)
rows = 4
cols = 4
arr = AutoFill(rows, cols)
print(arr)
print(Rearrange(arr))

输出:

[[-5 -4 -4  0]
 [-3  5 -1 -1]
 [ 4 -2  4 -5]
 [ 4  5 -3  1]]
[[-5 -4 -4  0]
 [-3  5 -1 -1]
 [ 4  5 -3  1]
 [ 4 -2  4 -5]]