组合任意长度的多个列表 [英] Combining multiple Lists of arbitrary length

查看:33
本文介绍了组合任意长度的多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种以下列方式加入多个列表的方法:

I am looking for an approach to join multiple Lists in the following manner:

ListA a b c
ListB 1 2 3 4
ListC + # * § %
..
..
..

Resulting List: a 1 + b 2 # c 3 * 4 § %

In Words:按顺序排列的元素,从第一个列表开始合并到结果列表中.任意数量的输入列表的长度可能会有所不同.

In Words: The elements in sequential order, starting at first list combined into the resulting list. An arbitrary amount of input lists could be there varying in length.

我使用了多种 zip 变体、滑动迭代器的方法,但都没有奏效,尤其是处理不同的列表长度.Scala 中必须有一种优雅的方式;)

I used multiple approaches with variants of zip, sliding iterators but none worked and especially took care of varying list lengths. There has to be an elegant way in scala ;)

推荐答案

val lists = List(ListA, ListB, ListC)

lists.flatMap(_.zipWithIndex).sortBy(_._2).map(_._1)

这是不言自明的.它只是压缩每个值及其在各自列表中的位置,按索引排序,然后将值拉回来.

It's pretty self-explanatory. It just zips each value with its position on its respective list, sorts by index, then pulls the values back out.

这篇关于组合任意长度的多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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