将一个数组分组以匹配另一个数组

时间:2019-07-10 01:19:56

标签: swift

我有一系列按月分组的日期。我试图对另一个值数组进行分组,使其与第一个数组匹配。有可能吗?

例如:

array1 = [[1,2,3],[4,5,6]]
array2 = ["one","two","three","four","five","six"]

我希望第二个数组与第一个数组分组在一起,以便它们匹配:

array2 = [["one","two","three"],["four","five","six"]]

2 个答案:

答案 0 :(得分:3)

思想的演变...

首先,是2D阵列的解决方案:

如果您知道array1是二维数组(元素数组组成的数组),则可以通过将array2变成迭代器并使用map和{{ 1}}替换元素:

compactMap

结果:

let array1 = [[1,2,3],[4,5,6]]
let array2 = ["one","two","three","four","five","six"]

var iter = array2.makeIterator()

let array3 = array1.map { arr in arr.compactMap { _ in iter.next() }}
print(array3)

更通用的通用解决方案:

这是使用序列而不是[["one", "two", "three"], ["four", "five", "six"]] 的更通用的解决方案,它不依赖于您提前知道array2的布局或数组值的类型或顺序:

array1

工作原理:

第二个数组或序列被转换为称为func remap<S: Sequence>(_ array: [Any], using sequence: S) -> [Any] { var iter = sequence.makeIterator() func remap(_ array: [Any]) -> [Any] { return array.compactMap { value in if let subarray = value as? [Any] { return remap(subarray) } else { return iter.next() } } } return remap(array) } 的迭代器,它使我们可以通过重复调用iter来获得值。

然后使用第二个递归版本iter.next()remap()转换为深度优先遍历的[Any][Any]用于替换数组的元素。在替换数组的元素时,如果元素是另一个数组,它将递归调用该数组上的compactMap(),直到最终得到的值不是数组。如果该元素是非数组元素,则将其替换为迭代器中的remap()值,该迭代器按顺序提供序列(或第二个数组)的元素。我们使用next而不是compactMap来处理map返回 optional 值的事实,因为它可能用完了值,在这种情况下它将返回{{1 }}。在这种情况下,iter.next()将不使用任何元素替换其余元素,同时仍保持第一个嵌套数组的结构。

示例:

nil
remap()
// replace Ints with Strings
let array1: [Any] = [1, [2, 3], [4, [5, 6]]]
let array2 = ["one","two","three","four","five","six"]

let array3 = remap(array1, using: array2)
print(array3)
["one", ["two", "three"], ["four", ["five", "six"]]]
// replace Strings with Ints
let array4: [Any] = ["a", ["b", "c"], [[["d"]], "e"]]
let array5 = [1, 2, 3, 4, 5]

let array6 = remap(array4, using: array5)
print(array6)
[1, [2, 3], [[[4]], 5]]
// map letters to numbers starting with 5 using a partial range
print(remap(["a", ["b"], ["c", ["d"]]], using: 5...))
[5, [6], [7, [8]]]
// using stride to create a sequence of even numbers
let evens = stride(from: 2, to: Int.max, by: 2)
print(remap([["a", "b"], ["c"], [["d"]]], using: evens))
[[2, 4], [6], [[8]]]

答案 1 :(得分:-3)

您可以使用numpy.array而不是list,如下所示:

import numpy as np

arr2 = ["one","two","three","four","five","six"]
arr3 = np.array(arr2).reshape(2,3)

arr3

结果:

array([['one', 'two', 'three'],
       ['four', 'five', 'six']], dtype='<U5')