按范围遍历数组 [英] Iterating over an array by range

查看:103
本文介绍了按范围遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:[1, 2, 3, 4, 5, 6...100]

我希望对该数组进行5次迭代,具体是:

I am looking to iterate over this array by 5, specifically:

取数组的前5个数字并获得平均值,移至下5个数字并获得平均值,依此类推.

Take the first 5 numbers of the array and get the average, move on to the next 5 numbers and get the average, and so on..

我尝试了许多方法,例如Dequeue和for循环,但未能获得所需的结果.

I have tried numerous methods such as a Dequeue and for loops but have not been able to get the outcome desired.

推荐答案

您需要使用级数循环来迭代每5个元素,并使用reduce对子序列求和,然后将总数除以子序列元素数:

You need to use a progression loop to iterate each 5 element and use reduce to sum the subsequence then divide the total by the subsequence elements count:

let sequence = Array(1...100)
var results: [Double] = []

for idx in stride(from: sequence.indices.lowerBound, to: sequence.indices.upperBound, by: 5) {
    let subsequence = sequence[idx..<min(idx.advanced(by: 5), sequence.count)]
    let average = Double(subsequence.reduce(0, +)) / Double(subsequence.count)
    results.append(average)
}
results   // [3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58, 63, 68, 73, 78, 83, 88, 93, 98]

这篇关于按范围遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆