python - Go 中的 slice 可以像 Python 的 list 一样成倍增加吗?
问题描述
这是 Python 示例:
s = ["push", "pop"] * 10
如何在 Go 中做到这一点?
解决方案
乘以 for 循环。没有内置任何东西。
in := []string{"push", "pop"}
n := 10
out := make([]string, 0, len(in)*n) // allocate space for the entire result
for i := 0; i < n; i++ { // for each repetition...
out = append(out, in...) // append, append, ....
}
fmt.Println(out) // prints [push pop push pop push pop push pop push pop push pop push pop push pop push pop push pop]
使用反射包编写通用乘法器:
// multiply repeats the slice src n times to the slice pointed to by destiny.
func multiply(src interface{}, n int, dstp interface{}) {
srcv := reflect.ValueOf(src)
result := reflect.MakeSlice(srcv.Type(), 0, srcv.Len()*n)
for i := 0; i < n; i++ {
result = reflect.AppendSlice(result, srcv)
}
reflect.ValueOf(dstp).Elem().Set(result)
}
in := []string{"push", "pop"}
var out []string
repeat(in, 10, &out)
fmt.Println(out) // prints [push pop push pop push pop push pop push pop push pop push pop push pop push pop push pop]
推荐阅读
- wordpress - Wordpress Themify,它如何自动生成样式表
- android - 创建补丁 APK 文件
- python - Python Regex - 使用 re.sub 清理字符串
- pivot-table - APEX 5:在 IR Pivot 中添加小计
- bash - bash 从 urls.txt 获取目录名
- mysql - MYSQL:如何获得行级别的安全性?
- unity3d - 身份验证未授权
- google-apps-script - setFormulasR1C1 可能没有#ERROR!?
- python - MSSQL 更新语句 - 字符串或二进制数据将被截断。[pyodbc]
- reporting - Odoo 10 QWeb 编码不正确