迅速拆分数组的优雅方法

编程入门 行业动态 更新时间:2024-10-06 15:19:45
本文介绍了迅速拆分数组的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出任何类型的数组和所需数量的子数组,我需要此输出:

Given an array of any kind and the wanted number of subarray, i need this output :

print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3)) // [[0, 3, 6], [1, 4], [2, 5]]

即使没有足够"的子数组,输出也必须包含正确数目的子数组.元素来填充那些:

Output must contain the correct number of subarrays even if there is not "enough" elements to fill those :

print([0, 1, 2].splitInSubArrays(into: 4)) // [[0], [1], [2], []]

我现在有这个可行的实现,但是有一种更好(更优雅)的方式来实现此输出:

I have this working implementation for now but is there a better (more elegant) way of achieving this output :

extension Array { func splitInSubArrays(into size: Int) -> [[Element]] { var output: [[Element]] = [] (0..<size).forEach { var subArray: [Element] = [] for elem in stride(from: $0, to: count, by: size) { subArray.append(self[elem]) } output.append(subArray) } return output } }

推荐答案

您可以用 map()操作替换两个循环:

You can replace both loops with a map() operation:

extension Array { func splitInSubArrays(into size: Int) -> [[Element]] { return (0..<size).map { stride(from: $0, to: count, by: size).map { self[$0] } } } }

外部 map()将每个偏移量映射到相应的数组,内部 map()将索引映射到数组元素.

The outer map() maps each offset to the corresponding array, and the inner map() maps the indices to the array elements.

示例:

print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3)) // [[0, 3, 6], [1, 4], [2, 5]] print([0, 1, 2].splitInSubArrays(into: 4)) // [[0], [1], [2], []]

更多推荐

迅速拆分数组的优雅方法

本文发布于:2023-11-30 15:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   优雅   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!