dlang 中的关联数组是否有类似 python popitem 的方法?

Is there method like python popitem for associative arrays in dlang?

我想从关联数组中获取任何 key/value 对并将其删除。 在 python 中是:

key, value = assoc.popitem()

在 D 中我做的是:

auto key = assoc.byKey.front;
auto value = assoc[key];
assoc.remove(key);

有更好的方法吗?是否可以在 foreach 之外使用 byKeyValue()?

DMD 2.067.1

Is it possible to use byKeyValue() outside foreach?

当然可以:

import std.stdio;

void main()
{
    int[string] assoc = ["apples" : 2, "bananas" : 4];

    while (!assoc.byKeyValue.empty)
    {
        auto pair = assoc.byKeyValue.front;
        assoc.remove(pair.key);
        writeln(pair.key, ": ", pair.value);
    }
}

Is there better way to do this?

我认为 D 没有与 popitem 等效的库函数。

在考虑之前,我会指出您可以编写一个简单的函数:

import std.typecons;

Tuple!(K, V) popitem(K, V)(ref V[K] arr) { 
    foreach(k, v; arr) { 
        arr.remove(k); 
        return tuple(k, v); 
    } 
    throw new Exception("empty!"); 
} 
void main() { 
    int[string] cool; 
    cool["ten"] = 10; 
    cool["twenty"] = 20; 
    import std.stdio; 
    writeln(cool.popitem()); 
    writeln(cool.popitem()); 
}

或使用 byKeyValue:

auto popitem(K, V)(ref V[K] arr) { 
    foreach(item; arr.byKeyValue()) { 
        arr.remove(item.key); 
        return item; 
    } 
    throw new Exception("empty!"); 
} 
void main() { 
    int[string] cool; 
    cool["ten"] = 10; 
    cool["twenty"] = 20; 
    import std.stdio; 
    auto item = cool.popitem(); 
    writeln(item.key, item.value); 
    item = cool.popitem(); 
    writeln(item.key, item.value); 
}   

一般来说,我喜欢鼓励人们不要害怕编写自己的函数。如果你可以用一些现有的东西来表达一些东西,那就写你自己的函数,给它一个你喜欢的名字,然后使用它!使用统一的函数调用语法,您甚至可以轻松地为内置类型编写扩展方法,就像我在这里所做的那样,并像它一直存在一样使用它。