寻找一个相当于python过滤器的飞镖
a = ['', None,4]
[print(e) for e in filter(None,a)]
Run Code Online (Sandbox Code Playgroud)
我的代码太丑了:
List a = [null,2,null];
List b=new List();
for(var e in a){if(e==null) b.add(e);}
for(var e in b){a.remove(e);}
print(a);
Run Code Online (Sandbox Code Playgroud)
Voi*_*ler 61
对于空安全,如果结果列表的类型不可为空,则旧的removeWhere解决方案将不再起作用。在removeWhere之后进行强制转换也不起作用。
最好的选择是导入集合
import 'package:collection/collection.dart';
Run Code Online (Sandbox Code Playgroud)
这允许人们做
import 'package:collection/collection.dart';
Run Code Online (Sandbox Code Playgroud)
小智 44
在具有声音零安全性的新飞镖 2.12 中,最好的方法是:
List<int?> a = [null,2,null];
final List<int> b = a.whereType<int>().toList();
Run Code Online (Sandbox Code Playgroud)
stw*_*ton 15
您可以使用List的removeWhere
方法,如下所示:
List a = [null, 2, null];
a.removeWhere((value) => value == null);
print(a); // prints [2]
Run Code Online (Sandbox Code Playgroud)
在现代 Dart 中,您可以使用“collection if”和“collection for”,它们类似于 Python 的列表推导式:
List a = [null, 2, null];
List b = [for (var i in a) if (i != null) i];
print(b); // prints [2]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2817 次 |
最近记录: |