filter - 为什么过滤器不适用于字符串列表
问题描述
我正在尝试编写代码来读取文本文件并过滤掉具有两个搜索项的行:
import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;
void main(){
string[] srchitems = ["second", "pen"]; // to search file text for lines which have both these;
auto alltext = readText("testing.txt");
auto alllist = alltext.split("\n");
foreach(str; srchitems){
alllist = alllist.filter!(a => a.indexOf(str) >= 0); // not working ;
}
writeln(alllist);
}
但是,它不起作用并给出此错误:
$ rdmd soq_filter.d
soq_filter.d(11): Error: cannot implicitly convert expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_filter.d", "-I."]
遵循演员阵容也不起作用:
alllist = cast(string[]) alllist.filter!(a => a.indexOf(str) >= 0); // not working ;
错误:
Error: cannot cast expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
问题出在哪里,如何解决?谢谢。
解决方案
如您所知, from 的返回值filter
不是数组,而是自定义范围。filter
的返回值实际上是一个惰性范围,因此如果您只使用前几个项目,则只会计算这些项目。要将惰性范围转换为数组,您需要使用std.array.array
:
import std.array : array;
alllist = alllist.filter!(a => a.indexOf(str) >= 0).array;
在你的情况下,这似乎运作良好。但是,通过稍微重构您的代码,有一个更惯用的解决方案:
import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;
import std.array;
void main() {
string[] srchitems = ["second", "pen"];
auto alltext = readText("testing.txt");
auto alllist = alltext.split("\n");
auto results = alllist.filter!(a => srchitems.any!(b => a.indexOf(b) >= 0));
writeln(results);
}
在上面的代码中,我们filter
直接使用了结果,而不是将其转换为数组。
推荐阅读
- reactjs - 为什么我的 ImageBackground 不再延伸到屏幕底部?
- maven - Wildfly swarm - 找不到页面错误
- css - bs4 自定义选择无法正常工作
- asynchronous - 带 EXIF 旋转校正的多图像上传
- android - Realm sort() - 基于字符串或整数的排序
- jenkins - 当两个并行线程尝试还原同一个包时,NuGet 还原包崩溃
- javascript - 使用 p5.js 为矩形着色
- guzzle - 如何使用 Guzzle 检索 HTTP 状态码?
- postgresql - Golden Gate 复制 - Postgres 实例
- ios - 如何在 UIDatePicker 中禁用特定日期