arrays - 将项目从子数组列表分发到其他子数组/有时会随机出错
问题描述
我有一个创建数组列表的程序。第一个数组填充了值,而其他数组可以为空,也可以不为空。如果它是空的,我们从第一个数组中取一个值并移动到一个空数组。目标是永远不要在列表中有一个空数组
Array Values
A1 -> V1, V2, V3, V4, V5 // add extra val to whatever is nxt in line
A2 <------|----------| //add A1[0][1] and A1[0][4] since its extra
A3 <----------| //add A1[0][2]
A4 <--------------| //add A1[0][3]
这就是我所拥有的。我感到困惑的是,它会随机使索引超出范围,而有时它会起作用,我相信有一种更优化和更有效的方法来做到这一点。我很乐意看看。
package main
import "fmt"
func main(){
//Create list of arrays
something := []string{"first", "second", "third"}
something2 := []string{""}
something3 := []string{""}
thisMap := make(map[int] []string, 0)
//assign them
thisMap[0] = something
thisMap[1] = something2
thisMap[2] = something3
//loop through the maps
for k, v := range thisMap{
//if the key is great than 0
if k > 0 {
//loop through the array
for _, items := range v {
//if the item is empty
if items == "" {
//we remove the empty string since we dont need it
v = v[1:]
//append the k value from the first array to the k array
v = append(v, thisMap[0][k])
//We update the array and remove the item we just assigned from the initial array
thisMap[0] = append(thisMap[0][:k], thisMap[0][k+1:]...)
}
}
//Assign the arrays back to the map
thisMap[k] = v
}
}
fmt.Println(thisMap)
}
解决方案
问题出在这一行:
v = append(v, thisMap[0][k])
在这里,您假设 的长度thisMap[0]
至少为 k,如果例如k
为 2 并且thisMap[0]
只剩下一个元素,则这是错误的。
由于映射键/值对的迭代以随机顺序发生,如果幸运的话,顺序将是 2、1、0,一切都会正常进行。如果运气不好,可能会出现超出范围的问题。
k
您应该获取第一个元素或最后一个元素或随机元素,而不是从位置选择thisMap[0]
元素,但始终考虑 的当前长度thisMap[0]
。
我关于代码组织的两分钱:
thisMap[0]
并且地图的其他条目显然在您的算法中扮演着不同的角色。所以你应该命名你的变量并组织你的代码来反映这一点。例如,您可以编写一个函数,它接受一个 [] 字符串,并返回一个 map[int][] 字符串,甚至可能是一个 [][] 字符串- 我认为使用内部单个空字符串初始化输出列表,稍后将其删除会引入不必要的噪音,您可以初始化空输出列表。另外,我不确定这部分的实现是否正确!
推荐阅读
- scala - 我应该如何在 scala 中实现“添加”解释器?
- angular - Angular,通过创建该类的“实例”和使用“this”关键字来调用类方法是否相同?
- reactjs - 如何从 URL 恢复组件状态
- autohotkey - 如何在 WinTitle 参数中使用 AutoHotkey 实例变量?
- javascript - iframe 施加的所有威胁是什么?
- python - 如何使用 selenium python 从网站下载图像
- python - 新生AttributeError:模块中没有属性
- c++ - 使用此指针的 fltk 回调问题
- reactjs - 在 redux 状态中存储 ref 是不好的做法吗?
- javascript - 根据一天显示不同的时间