本文介绍了如何检查列表是否包含列表,以及如何从列表中删除列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 .contains

搜索列表以查看是否包含另一个列表。

However, it doesn't work.

void main() {
  List cake = [[true, 8728], [true, 3231], [true, 9981], [true, 4323], [true, 6456], [true, 3244], [true, 4355]];
  print(cake.contains([true, 9981])); // Prints false, although cake contains [true, 9981]
  List piece = [true, 9981];
  cake.remove(piece); // Does not remove [true, 9981] from the List cake
  print(cake); // List remains unaltered
}

我假设 .contains .remove 不能从列表中搜索或删除列表?难道我做错了什么?否则,除了遍历列表,最好的方法是做什么?

I assume .contains and .remove can't search for or remove a List from a List? Am I doing something wrong? Otherwise, what's the best way to do what I'm trying to do, other than looping through the list?

推荐答案

您的问题是 List< E> ;.包含 List< E> ;.删除(以及其他 List 方法)使用 E.operator == 来匹配该项目,但您的元素类型为 List 和仅检查对象身份,而不执行深度相等性检查。 (即 [1] == [1] false ,因为每个实例[1] 是一个单独的 List 对象。)

Your problem is that List<E>.contains and List<E>.remove (among other List methods) use E.operator == to match the item, but your element type is List, and List.operator == checks only for object identity instead of performing a deep equality check. (That is, [1] == [1] is false because each instance of [1] is a separate List object.)

一种执行所需操作的方法是使用和。

One way to do what you want is instead to use List.removeWhere with a deep List equality check.

这篇关于如何检查列表是否包含列表,以及如何从列表中删除列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:21