dsgdf45654 2015-06-26 18:55
浏览 21
已采纳

按转到列表中的值删除元素

I have a list of elements and I want to remove one of them, by value. In Python this would be

l = ["apples", "oranges", "melon"]
l.remove("melon")
print(l) # ["apples", "orange"]

What is the equivalent in Go? I found a slice trick to remove an element by index, but it's not very readable, still requires me to find the index manually and only works for a single item type:

func remove(l []string, item string) {
    for i, other := range l {
        if other == item {
            return append(l[:i], l[i+1:]...)
        }
    }
}

There's the list.List structure, but it's not generic and thus requires tons of type-castings to use.

What is the idiomatic way of removing an element from a list?

  • 写回答

1条回答 默认 最新

  • duancheng3342 2015-06-26 19:10
    关注

    The idiomatic way to remove an element from a list is to loop through it exactly like you do in your example. Removing an element by value from a slice shouldn't be too common in your program since it is an O(n) operation and there are better data structures in the language for that. Therefore, Go does not provide a built-in remove function for slices.

    If you find yourself using removal by value often, consider using a set instead where removing and adding an element is O(1) while still being iterable.

    set := map[string]bool{"apples":true, "oranges":true, "melon":true}
    delete(set,"melon") // is O(1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办