我想檢查一組串列中是否已經存在字典。如果不使用any()in if-statement,我收到以下錯誤:
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]}]
uj5u.com熱心網友回復:
問題歸結為這樣一個事實:與大多數型別不同,您不能單獨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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451324.html
