将第一个列表的元素分发给另一个 list/array

Distribute elements of the fist list to another list/array

我有一个Array[(List(String)), Array[(Int, Int)]]这样的

 ((123, 456, 789), (1, 24))
 ((89, 284), (2, 6))
 ((125, 173, 88, 222), (3, 4))

我想将第一个列表的每个元素分配给第二个列表,像这样

 (123, (1, 24))
 (456, (1, 24))
 (789, (1, 24))
 (89, (2, 6))
 (284, (2, 6))
 (125, (3, 4))
 (173, (3, 4))
 (88, (3, 4))
 (22, (3, 4))

谁能帮我解决这个问题?非常感谢。

输入数据定义如下:

val data = Array((List("123", "456", "789"), (1, 24)), (List("89", "284"), (2, 6)), (List("125", "173", "88", "222"), (3, 4)))

您可以使用:

data.flatMap { case (l, ii) => l.map((_, ii)) }

产生:

Array[(String, (Int, Int))] = Array(("123", (1, 24)), ("456", (1, 24)), ("789", (1, 24)), ("89", (2, 6)), ("284", (2, 6)), ("125", (3, 4)), ("173", (3, 4)), ("88", (3, 4)), ("222", (3, 4)))

我认为这符合您的要求。

根据您的示例,在我看来您使用的是单一类型。

scala> val xs: List[(List[Int], (Int, Int))] = 
     |   List( ( List(123, 456, 789), (1, 24) ), 
     |         ( List(89, 284), (2,6)), 
     |         ( List(125, 173, 88, 222), (3, 4)) )
xs: List[(List[Int], (Int, Int))] = List((List(123, 456, 789), (1,24)),
                                         (List(89, 284),(2,6)),
                                         (List(125, 173, 88, 222),(3,4)))

然后我写了这个函数:

scala> def f[A](xs: List[(List[A], (A, A))]): List[(A, (A, A))] = 
     |     for {
     |       x    <- xs
     |       head <- x._1
     |     } yield (head, x._2)
f: [A](xs: List[(List[A], (A, A))])List[(A, (A, A))]

f应用到xs

scala> f(xs)
res9: List[(Int, (Int, Int))] = List((123,(1,24)), (456,(1,24)), 
             (789,(1,24)), (89,(2,6)), (284,(2,6)), (125,(3,4)), 
                 (173,(3,4)), (88,(3,4)), (222,(3,4)))