如何从一个切片中分离出数字?

huangapple go评论104阅读模式
英文:

How to separate numbers from a slice?

问题

让我们假设我有一个包含10个数字的列表:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

我想让我的程序每次切片三个数字,例如:

[1,2,3]
[4,5,6]
[7,8,9]

我该如何实现呢?
感谢您的提问!

英文:

Let's say I have a list with 10 numbers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I would like my program to slice every 3 numbers, for example:

[1,2,3]
[4,5,6]
[7,8,9]

How can I do it?
Grateful

答案1

得分: 1

例如,当 n = 3 时,

package main

import "fmt"

func main() {
    list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    for a, n := list, 3; len(a) >= n; a = a[n:] {
        slice := a[:n]
        fmt.Println(slice)
    }
}

输出结果:

[1 2 3]
[4 5 6]
[7 8 9]
英文:

For example, with n = 3,

package main

import "fmt"

func main() {
	list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	for a, n := list, 3; len(a) >= n; a = a[n:] {
		slice := a[:n]
		fmt.Println(slice)
	}
}

Output:

[1 2 3]
[4 5 6]
[7 8 9]

答案2

得分: -2

你可以像这样制作一个类似的东西(对于伪代码表示抱歉):

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while array:
    my_list = []
    for i in range(3):
        my_list.append(array[i])
        del array[i]
    print("your list now here:", my_list)

你可以先询问前三个值,然后将其移除。

英文:

you could make a something like this (sorry for pseudo code)

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while (array){
    list = ""
    for($i=1;$i -le 3;$i++){
    list.add = array[$i]
    remove from array the array[$i]
    }
    your list now here (list)

}

you could ask the first 3 values and after that you remove it

huangapple
  • 本文由 发表于 2017年5月14日 04:54:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/43957893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定