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

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

How to separate numbers from a slice?

问题

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

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

  1. [1,2,3]
  2. [4,5,6]
  3. [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. [1,2,3]
  2. [4,5,6]
  3. [7,8,9]

How can I do it?
Grateful

答案1

得分: 1

例如,当 n = 3 时,

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

输出结果:

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

For example, with n = 3,

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

Output:

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

答案2

得分: -2

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

  1. array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. while array:
  3. my_list = []
  4. for i in range(3):
  5. my_list.append(array[i])
  6. del array[i]
  7. print("your list now here:", my_list)

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

英文:

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

  1. array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. while (array){
  3. list = ""
  4. for($i=1;$i -le 3;$i++){
  5. list.add = array[$i]
  6. remove from array the array[$i]
  7. }
  8. your list now here (list)
  9. }

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:

确定