digitalmars.D.learn - Filtering Associative Array Key-Values the D way
- David DeWitt (23/23) Jun 24 2015 I'm trying to understand filtering an Associative Array the D
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (22/42) Jun 24 2015 It would be more efficient to filter the input before creating a larger
I'm trying to understand filtering an Associative Array the D way. I have the code below (Using while readln cause problem failing on Debian using byLineCopy()). When the byKeyValue().filter evaluates to reduce the number of Keys:Values to only the ones in the filtered header, what is the best way to transform the Pair back to an AA instead of having to run the foreach loop after? Basically if the file has 300 columns and 300 in the full header but only 15 in the filtered header I want the return of rec to only be the 15 in an Associative Array. Thanks :) string line; string[string][] records; while ((line = f.readln()) !is null){ string[string] record; auto rec = assocArray(zip(h1.fullHeader, splitter(line,','))) .byKeyValue().filter!(a=>h1.filteredHeader.canFind(a.key)); foreach(r;rec){ record[r.key] = r.value; } records ~= record; }
Jun 24 2015
On 06/24/2015 09:08 AM, David DeWitt wrote:I'm trying to understand filtering an Associative Array the D way. I have the code below (Using while readln cause problem failing on Debian using byLineCopy()). When the byKeyValue().filter evaluates to reduce the number of Keys:Values to only the ones in the filtered header, what is the best way to transform the Pair back to an AA instead of having to run the foreach loop after? Basically if the file has 300 columns and 300 in the full header but only 15 in the filtered header I want the return of rec to only be the 15 in an Associative Array. Thanks :) string line; string[string][] records; while ((line = f.readln()) !is null){ string[string] record; auto rec = assocArray(zip(h1.fullHeader, splitter(line,','))) .byKeyValue().filter!(a=>h1.filteredHeader.canFind(a.key)); foreach(r;rec){ record[r.key] = r.value; } records ~= record; }It would be more efficient to filter the input before creating a larger AA to be thrown away: import std.stdio; import std.range; import std.algorithm; void main() { auto keys = 10.iota; auto values = keys.map!(k => 10 * k); auto result = zip(keys, values) .filter!(t => t[0] % 2) .assocArray; writefln("%(%s: %s\n%)", result); } The AA contains elements with odd keys: 1: 10 5: 50 9: 90 3: 30 7: 70 Ali
Jun 24 2015