在scala中将列表转换为多个元组
我有以下元组:1,3白痴、ListAction、冒险、恐怖,我需要将它们转换为以下格式的列表:在scala中将列表转换为多个元组,scala,Scala,我有以下元组:1,3白痴、ListAction、冒险、恐怖,我需要将它们转换为以下格式的列表: List( (1,"3idiots","Action"), (1,"3idiots","Adventure") ) 假设您有多个元组,如下所示: val tuples = List( (1, "3idiots", List("Action", "Adventure", "Horror")), (2, "foobar", List("Foo", "Bar")) ) List(
List(
(1,"3idiots","Action"),
(1,"3idiots","Adventure")
)
假设您有多个元组,如下所示:
val tuples = List(
(1, "3idiots", List("Action", "Adventure", "Horror")),
(2, "foobar", List("Foo", "Bar"))
)
List(
(1, "3idiots", "Action"),
(1, "3idiots" , "Adventure"),
(1, "3idiots", "Horror"),
(2, "foobar", "Foo"),
(2, "foobar", "Bar")
)
你想要这样的结果:
val tuples = List(
(1, "3idiots", List("Action", "Adventure", "Horror")),
(2, "foobar", List("Foo", "Bar"))
)
List(
(1, "3idiots", "Action"),
(1, "3idiots" , "Adventure"),
(1, "3idiots", "Horror"),
(2, "foobar", "Foo"),
(2, "foobar", "Bar")
)
您的解决方案是使用flatMap,它可以将列表列表转换为单个列表:
tuples.flatMap(t =>
t._3.map(s =>
(t._1, t._2, s)
)
)
或者更短:tuples.flatmap=>t._3.mapt._1,t._2,假设您有多个这样的元组:
val tuples = List(
(1, "3idiots", List("Action", "Adventure", "Horror")),
(2, "foobar", List("Foo", "Bar"))
)
List(
(1, "3idiots", "Action"),
(1, "3idiots" , "Adventure"),
(1, "3idiots", "Horror"),
(2, "foobar", "Foo"),
(2, "foobar", "Bar")
)
你想要这样的结果:
val tuples = List(
(1, "3idiots", List("Action", "Adventure", "Horror")),
(2, "foobar", List("Foo", "Bar"))
)
List(
(1, "3idiots", "Action"),
(1, "3idiots" , "Adventure"),
(1, "3idiots", "Horror"),
(2, "foobar", "Foo"),
(2, "foobar", "Bar")
)
您的解决方案是使用flatMap,它可以将列表列表转换为单个列表:
tuples.flatMap(t =>
t._3.map(s =>
(t._1, t._2, s)
)
)
或者更短:tuples.flatMapt=>t._3.mapt._1,t._2,u这应该满足您的需要:
val input = (1,"3idiots",List("Action","Adventure","Horror"))
val result = input._3.map(x => (input._1,input._2,x))
// gives List((1,3idiots,Action), (1,3idiots,Adventure), (1,3idiots,Horror))
这应该满足您的要求:
val input = (1,"3idiots",List("Action","Adventure","Horror"))
val result = input._3.map(x => (input._1,input._2,x))
// gives List((1,3idiots,Action), (1,3idiots,Adventure), (1,3idiots,Horror))
若要添加到先前的答案中,您也可以在本例中使用以进行理解;这可能会让事情变得更清楚:
for(
(a,b,l) <- ts;
s <- l
) yield (a,b,s)
您将获得:
List(
(a,1,foo),
(a,1,bar),
(a,1,baz),
(b,2,foo1),
(b,2,bar1),
(b,2,baz1)
)
若要添加到先前的答案中,您也可以在本例中使用以进行理解;这可能会让事情变得更清楚:
for(
(a,b,l) <- ts;
s <- l
) yield (a,b,s)
您将获得:
List(
(a,1,foo),
(a,1,bar),
(a,1,baz),
(b,2,foo1),
(b,2,bar1),
(b,2,baz1)
)
你可以用这个
val question = (1,"3idiots",List("Action","Adventure","Horror"))
val result = question._3.map(x=> (question._1 , question._2 ,x))
你可以用这个
val question = (1,"3idiots",List("Action","Adventure","Horror"))
val result = question._3.map(x=> (question._1 , question._2 ,x))
请添加代码?那么您尝试了什么?你被困在哪里?你认为哪些功能有用?您已经阅读了文档,对吗?提示:FlatMap和恐怖如何?请添加代码?那么您尝试了什么?你被困在哪里?你认为哪些功能有用?您已经阅读了文档,对吗?提示:那恐怖呢?