为什么过滤器不适用于字符串列表

恩索

我正在尝试编写代码以读取文本文件并过滤出同时具有两个搜索项的行:

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[]

问题在哪里,如何解决?谢谢。

BioTronic

如您所知,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直接使用结果,而不是将其转换为数组。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章