首页 > 解决方案 > 两个嵌套列表的差异。错误:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

问题描述

我想获得那些new_pattern_dataset不存在于all_pattern_dataset. 我正在编写以下代码:

new_pattern_dataset=[x for x in new_pattern_dataset if x not in all_pattern_dataset]

在哪里

print(type(new_pattern_dataset))
new_pattern_dataset
OUTPUT:
[(1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0),
 (0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1),
.
.
.
(1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0),
 ...]
print(type(all_pattern_dataset))
all_pattern_dataset
OUTPUT:
<class 'list'>
[array([0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1]),
 array([0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1]),
.
.
.
array([0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0]),
 ...]

这给了我错误:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 有人可以解释我做错了什么以及如何纠正它吗?

另外,由于两者的类型都是new_pattern_datasetall_pattern_dataset列表”,为什么它们有不同的格式?

标签: pythonnested-listsnumpy-ndarray

解决方案


将一个列表与另一个列表进行比较可能会很棘手,因为 python 不知道您是否要将列表/子列表中的每个元素与另一个列表的元素或列表本身进行比较。

因此,您会收到错误消息:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 您可以通过处理字符串等子列表来解决此问题:

new_pattern_dataset = [str(x) for x in new_pattern_dataset if str(x) not in [str(list(y)) for y in all_pattern_dataset]]

获得差异的另一种方法是使用集合,因为与列表相反,集合本身允许检查 2 个集合之间的差异:

new_pattern_dataset = list(set(str(x) for x in new_pattern_dataset) - set([str(list(y)) for y in all_pattern_dataset]]))

推荐阅读