如何使用 Scala 和 Spark select 数组中的非顺序子集元素?
How can I select a non-sequential subset elements from an array using Scala and Spark?
在Python中,我会这样做。
>>> x
array([10, 9, 8, 7, 6, 5, 4, 3, 2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])
这在 Scala Spark 中不起作用 shell:
scala> val indices = Array(3,2,0)
indices: Array[Int] = Array(3, 2, 0)
scala> val A = Array(10,11,12,13,14,15)
A: Array[Int] = Array(10, 11, 12, 13, 14, 15)
scala> A(indices)
<console>:28: error: type mismatch;
found : Array[Int]
required: Int
A(indices)
foreach方法也不行:
scala> indices.foreach(println(_))
3
2
0
scala> indices.foreach(A(_))
<no output>
我要的是B的结果:
scala> val B = Array(A(3),A(2),A(0))
B: Array[Int] = Array(13, 12, 10)
但是,我不想像那样对其进行硬编码,因为我不知道索引有多长或其中包含什么。
我能想到的最简洁的方法是翻转你的心智模型,把索引放在第一位:
indices map A
而且,我可能会建议使用 lift
到 return 和 Option
indices map A.lift
您可以在 indices
上使用 map
,它根据映射 lambda 将每个元素映射到一个新元素。请注意,在 Array
上,您使用 apply
方法在索引处获取一个元素:
indices.map(index => A.apply(index))
你可以离开 apply
:
indices.map(index => A(index))
您也可以使用下划线语法:
indices.map(A(_))
遇到这种情况,下划线也可以去掉:
indices.map(A)
您可以使用备用 space 语法:
indices map A
您尝试使用 foreach
,returns Unit
,并且仅用于副作用。例如:
indices.foreach(index => println(A(index)))
indices.map(A).foreach(println)
indices map A foreach println
在Python中,我会这样做。
>>> x
array([10, 9, 8, 7, 6, 5, 4, 3, 2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])
这在 Scala Spark 中不起作用 shell:
scala> val indices = Array(3,2,0)
indices: Array[Int] = Array(3, 2, 0)
scala> val A = Array(10,11,12,13,14,15)
A: Array[Int] = Array(10, 11, 12, 13, 14, 15)
scala> A(indices)
<console>:28: error: type mismatch;
found : Array[Int]
required: Int
A(indices)
foreach方法也不行:
scala> indices.foreach(println(_))
3
2
0
scala> indices.foreach(A(_))
<no output>
我要的是B的结果:
scala> val B = Array(A(3),A(2),A(0))
B: Array[Int] = Array(13, 12, 10)
但是,我不想像那样对其进行硬编码,因为我不知道索引有多长或其中包含什么。
我能想到的最简洁的方法是翻转你的心智模型,把索引放在第一位:
indices map A
而且,我可能会建议使用 lift
到 return 和 Option
indices map A.lift
您可以在 indices
上使用 map
,它根据映射 lambda 将每个元素映射到一个新元素。请注意,在 Array
上,您使用 apply
方法在索引处获取一个元素:
indices.map(index => A.apply(index))
你可以离开 apply
:
indices.map(index => A(index))
您也可以使用下划线语法:
indices.map(A(_))
遇到这种情况,下划线也可以去掉:
indices.map(A)
您可以使用备用 space 语法:
indices map A
您尝试使用 foreach
,returns Unit
,并且仅用于副作用。例如:
indices.foreach(index => println(A(index)))
indices.map(A).foreach(println)
indices map A foreach println