在 Scala 中,是否可以压缩两个不同大小的列表? [英] In Scala, is it possible to zip two lists of differing sizes?

查看:38
本文介绍了在 Scala 中,是否可以压缩两个不同大小的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如假设我有

val letters = ('a', 'b', 'c', 'd', 'e')
val numbers = (1, 2)

是否可以生成一个列表

(('a',1), ('b',2), ('c',1),('d',2),('e',1))

推荐答案

您的字母和数字是元组,而不是列表.所以让我们解决这个问题

Your letters and numbers are tuples, not lists. So let's fix that

scala> val letters = List('a', 'b', 'c', 'd', 'e')
letters: List[Char] = List(a, b, c, d, e)

scala> val numbers = List(1,2)                    
numbers: List[Int] = List(1, 2)

现在,如果我们压缩它们,我们不会得到想要的结果

Now, if we zip them we don't get the desired result

scala> letters zip numbers
res11: List[(Char, Int)] = List((a,1), (b,2))

但这表明如果数字无限重复,那么问题就会解决

But that suggests that if numbers were repeated infinitely then the problem would be solved

scala> letters zip (Stream continually numbers).flatten
res12: List[(Char, Int)] = List((a,1), (b,2), (c,1), (d,2), (e,1))

不幸的是,这是基于数字比字母短的知识.所以把它全部解决

Unfortunately, that's based on knowledge that numbers is shorter than letters. So to fix it all up

scala> ((Stream continually letters).flatten zip (Stream continually numbers).flatten take (letters.size max numbers.size)).toList
res13: List[(Char, Int)] = List((a,1), (b,2), (c,1), (d,2), (e,1))

这篇关于在 Scala 中,是否可以压缩两个不同大小的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆