numpy.sort()error ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()

时间:2022-09-05 16:07:54

When I use numpy to sort an array this problem come up :

当我使用numpy对数组进行排序时,会出现这个问题:

Traceback (most recent call last):
File "D:/Desktop/LIP/complier/num/f_t.py", line 75, in <module>
frogs[i].sort(order='length')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But if I comment these codes,it is ok

但如果我评论这些代码,那就没关系

        # if len < temp_len:
        #     r_w[i]['length'] = len
        # else:
        #     r_w[i]['points'] = r_g['points']
        #     r_w[i]['length'] = r_g['length']

Why?

r_g is the best route,r_w are the worst routes in every group,r_b is the best route in every group. I want to change the worst route for 5 times in a loop.

r_g是最佳路由,r_w是每个组中最差的路由,r_b是每个组中的最佳路由。我想在一个循环中改变最差路线5次。

Here is the code:

这是代码:

# -*- coding: utf-8 -*- 
# __author__ = 'youzipi'
import numpy as np

def cal_length(route):
    length = 0
    for i in range(POINTS_NUM):
        p1 = points[route[i]]
        p2 = points[route[(i + 1) % POINTS_NUM]]
        length += np.linalg.norm(p1 - p2)
    return length

POINTS_NUM = 10
ROUTES_NUM = 50
routetype = np.dtype({
    'names': ['points', 'length'],
    'formats': ['O', 'f']})
routes = np.zeros([(ROUTES_NUM)], dtype=routetype)
points = np.random.rand(POINTS_NUM, 2) * 10
print "points=", points

for index in range(ROUTES_NUM):
    temp = np.random.permutation(range(POINTS_NUM))
    length = cal_length(temp)
    routes[index] = (temp, length)


print "after sort"
routes.sort(order=('length'))
print routes
frogs = np.zeros([5, 10], dtype=routetype)

for i in range(5):
    t = 0
    for j in range(ROUTES_NUM):
        if j%5 == i:
            frogs[i][j/5]['points'] = routes[j]['points']
            frogs[i][j/5]['length'] = routes[j]['length']

for i in range(5):
    print "frogs", i
    print frogs[i]
p = routes['length']
print p
r_g = routes[0]
print "r_g", r_g
r_b = frogs[:, 0]
print "r_b", r_b
r_w = frogs[:, 9]
print "r_w", r_w


#def update_frogs():
#global r_w, r_b, r_b
for i in range(5):
    for j in range(5):
        cut = int(np.random.rand(1)[0] * 10)
        ran = np.random.permutation(range(POINTS_NUM))
        print 'r_w', r_w[i]
        print 'r_b', r_b[i]
        temp_len = r_w[i]['length']
        r_w[i]['points'] = np.hstack((r_b[i]['points'][:cut], np.linspace(-1, -1, 10)[cut:]))
        for t in ran:
            if t not in r_w[i]['points']:
                r_w[i]['points'][cut] = t
                cut = cut + 1
            if cut >= POINTS_NUM:
                break
        len = cal_length(r_w[i]['points'])
        # if len < temp_len:
        #     r_w[i]['length'] = len
        # else:
        #     r_w[i]['points'] = r_g['points']
        #     r_w[i]['length'] = r_g['length']
        frogs[i].sort(order='length')#trackbreak here!!
        r_w[i]['points'] = frogs[i, 9]['points']
        r_w[i]['length'] = frogs[i, 9]['length']
        print "after"
        print 'f_w', r_w[i]
        print 'f_b', r_b[i]

1 个解决方案

#1


Look at the 'related' column - there are lots of questions about this ValueError.

查看“相关”列 - 有很多关于此ValueError的问题。

The most likely cause is that you generate a list or array of True/False values and then try to use it in a Python if/else context.

最可能的原因是您生成一个True / False值的列表或数组,然后尝试在Python if / else上下文中使用它。

So instead of holding your hand and analyzing all of your code, I'm going to suggest that you look at the variables in the those problem lines, and determine which are generating multiple values. Actually, since there is only on if statement, it has to be len < temp_len. Other or other of those 2 variables is a array, not a scalar.

因此,我不打算握住你的手并分析你的所有代码,而是建议你查看那些问题行中的变量,并确定哪些生成多个值。实际上,由于只有if语句,它必须是len 。这两个变量中的其他或另一个是数组,而不是标量。

    # if len < temp_len:
    #     r_w[i]['length'] = len
    # else:
    #     r_w[i]['points'] = r_g['points']
    #     r_w[i]['length'] = r_g['length']

#1


Look at the 'related' column - there are lots of questions about this ValueError.

查看“相关”列 - 有很多关于此ValueError的问题。

The most likely cause is that you generate a list or array of True/False values and then try to use it in a Python if/else context.

最可能的原因是您生成一个True / False值的列表或数组,然后尝试在Python if / else上下文中使用它。

So instead of holding your hand and analyzing all of your code, I'm going to suggest that you look at the variables in the those problem lines, and determine which are generating multiple values. Actually, since there is only on if statement, it has to be len < temp_len. Other or other of those 2 variables is a array, not a scalar.

因此,我不打算握住你的手并分析你的所有代码,而是建议你查看那些问题行中的变量,并确定哪些生成多个值。实际上,由于只有if语句,它必须是len 。这两个变量中的其他或另一个是数组,而不是标量。

    # if len < temp_len:
    #     r_w[i]['length'] = len
    # else:
    #     r_w[i]['points'] = r_g['points']
    #     r_w[i]['length'] = r_g['length']