简体   繁体   中英

python, list compare, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Here is my python code:

def ava_check(nodes_group,child_list):
    ava_list=nodes_group[:]

    if nodes_group[1] in child_list:
        return None
    else:
        for a in nodes_group:
            if a in child_list:
                ava_list.remove(a)
                ava_list.remove(nodes_group[nodes_group.index(a)-1])
            else:
                pass

The nodes_group is a list like [0.0, (0, 3), 0.0, (0, 2), 0.0, (1, 3)] . The child_list is a list like [(0, 1)] .

But when I run the code, there is an error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() happened in line if a in child_list: . I have no idea what is the problem here. I tried to search, but they said something about numpy. But I didn't use numpy here, the two inout arguments are just list with tuples.

Could you help me with this problem?

Thanks very much.

UPDATE: Thanks for everyone's solution. Some data (not tuples) in the list nodes_group are from the numpy array. But I store the data in new list. So I checked the data type of the element in the new list using type(), and I found that the type is numpy.float64 , which explains why I have this error. So I write a loop to change the type of element in list from numpy.float64 to int by just using int() . So the problem is solved. But anyone know whether is a better solution or more pythonic way? Thanks.

One (or more) of the values in your nodes_group list is a numpy array, not a float or tuple like you show in your example data. You can't use the test a in some_list if a is an array, because an array's == operator doesn't return a bool value, but rather a Boolean array. The Boolean array raises the exception you see when Python tries to covert it to a single bool .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM