如何在Dart中获取两个列表之间的差异?

4

我现在正在创建一个应用程序,想要获取两个列表之间的差异,例如:

List x = ['one' , 'two' , 'three' , 'four'];

List y = ['one' , 'two',];

------

Output: ['three' , 'four']

获取列表的差异(Flutter/Dart) - giorgio79
2个回答

12

如果你可以使用Set.difference,这可能会更容易。

如果你只能使用列表,那么这是一个略微缩短的解决方案。

    var l = [1, 2, 3, 4];
    var r = [3, 4];
    l.removeWhere((e) => r.contains(e));
    print(l);

如果您想检索一个新列表,可以使用 newList = l.where((e) => !r.contains(e)); - genericUser

2

您可以循环遍历其中一个列表,然后检查该项是否存在于另一个列表中。

void main() {
  List x = ['one' , 'two' , 'three' , 'four'];
  List y = ['one' , 'two',];
  List output = [];

  for(final e in x){
    bool found = false;
    for(final f in y) {
      if(e == f) {
        found = true;
        break;
      }
    }
    if(!found){
      output.add(e);
    }
  }
  print(output);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接