ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() - followed by a TypeError

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() - followed by a TypeError

我想检查一组列表中是否已经存在字典。在 if-statement 中没有使用 any(),我收到以下错误:

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

但是当我使用 any() 时,会出现以下错误:

TypeError: 'bool' object is not iterable

我不知道我哪里错了。如有任何帮助或指导,我们将不胜感激。

import numpy as np

compile = []
MY_LIST = [[['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]], [['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]], [['Tues'], np.array([3, 1, 2, 4]), ['text2'], ['more_text2', 0.2]]]
for group in MY_LIST:
    my_dict = {'A': group[0], 'B': group[1], 'C': group[2],
               'D': group[3]}

    if any(my_dict not in compile):  # Error here
        compile.append(my_dict)
    print (compile)

预期的输出应该是:

[{'A': ['Mon'], 'B': array([4, 2, 1, 3]), 'C': ['text'], 'D': ['more_text', 0.1]}, {'A': ['Tues'], 'B': array([3, 1, 2, 4]), 'C': ['text2'], 'D': ['more_text2', 0.2]}]

问题归结为您不能单独使用 == 直接比较两个 numpy 数组,这与大多数类型不同。您需要定义一个自定义函数来比较字典中的两个值以处理不同的类型:

import numpy as np

def compare_element(elem1, elem2):
    if type(elem1) != type(elem2):
        return False
    if isinstance(elem1, np.ndarray):
        return (elem1 == elem2).all()
    else:
        return elem1 == elem2

result = []
MY_LIST = [
    [['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]],
    [['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]],
    [['Tues'], np.array([3, 1, 2, 4]), ['text2'], ['more_text2', 0.2]]
]

for group in MY_LIST:
    elem_to_append = dict(zip(['A', 'B', 'C', 'D'], group))

    should_append = True
    for item in result:
        if all(compare_element(item[key], elem_to_append[key]) for key in item):
            should_append = False
            break

    if should_append:
        result.append(elem_to_append)

print(result)