python - 两个嵌套列表的差异。错误:具有多个元素的数组的真值不明确。使用 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_dataset
“all_pattern_dataset
列表”,为什么它们有不同的格式?
解决方案
将一个列表与另一个列表进行比较可能会很棘手,因为 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]]))
推荐阅读
- linker - 是否可以指示链接器将节标题内容放在哪里?
- python-3.x - Cartopy - 手动 set_extent
- azure - Azure bot builder 虚拟助手 - 在语言生成中使用 foreach 表达式
- c++ - Directx 11 - CompileFromFile() 未编译
- regex - Zend 中的正则表达式电子邮件验证
- python - 为什么我在运行我的 python ping 脚本时收到主机未找到错误?
- ios - 如何在 iOS 中对图像实现 XMP 预设过滤器
- r - 如何编写一个函数来根据控制数据集在 R 中剪切许多列
- javascript - 检查包含文档中所有对象ID的数组字段中是否存在对象ID的最佳方法是什么?
- python - 调用 plt.subplot() 重置子图大小