英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论