【问题标题】:make tuples scala string制作元组scala字符串
【发布时间】:2016-03-18 18:56:51
【问题描述】:

我有一个 Array[String] 的 RDD,如下所示:

 mystring= ['thisisastring', 'thisisastring', 'thisisastring', 'thisisastring' ......]

我需要将每个元素,或者每一行做成一个元组,它将固定数量的项目组合在一起,以便它们可以作为一个整体传递。 所以,本质上,它就像:

(1, 'thisisastring')
(2, 'thisisastring')
(3, 'thisisastring')

所以我想我需要使用Tuple2,即Tuple2[Int, String]。如果我错了,请提醒我。

当我这样做时:val vertice = Tuple2(1, mystring)。 我意识到我只是将 int 1 添加到每一行。 所以我需要一个循环遍历我的 Array[String],将 1、2 和 3 添加到第 1 行、第 2 行和第 3 行。 我考虑过使用 while(countval count是一个固定的数字,我不能每次都更新count的值。 您有更好的方法吗?

【问题讨论】:

  • 注意(A, B)等价于Tuple2(A, B)
  • 什么意思?
  • 如果我使用 zipwithindex,它会给我一个元组对吗? bcz 我要添加边和顶点,它们需要是元组
  • 我的意思是Scala中对元组有特殊的支持。包围 2 个项目,用逗号分隔,括号中创建一个 Tuple2,3 个项目创建一个 Tuple3,依此类推。

标签: scala loops tuples


【解决方案1】:

听起来您正在寻找 zipWithIndex。

您没有指定您希望生成的 RDD 的类型,但是
这会给你RDD[(Int, String)]:

rdd.flatMap(_.zipWithIndex)

这会给你RDD[Array[(Int, String)]:

rdd.map(_.zipWithIndex)

【讨论】:

  • 在这里回答您的一般性评论,因为它询问 zipWithIndex。是的 zip 和 zipWithIndex 都创建 Tuple2。
【解决方案2】:

使用 for & yield 怎么样。

for ( i <- 1 to count ) yield Tuple2(i, mystring(i) )

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多