如何压缩不同长度的列表? [英] How to zip lists with different length?

查看:57
本文介绍了如何压缩不同长度的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何 zip 像这样的两个列表

["Line1","Line2","Line3"]
["Line4","Line5"]

是否不丢弃第一个列表中的其余元素?

without discarding rest elements in first list?

如果可以的话,我想用空列表压缩其他元素.

I'd like to zip extra elements with empty list, if it can be done.

推荐答案

zipWithPadding :: a -> b -> [a] -> [b] -> [(a,b)]
zipWithPadding a b (x:xs) (y:ys) = (x,y) : zipWithPadding a b xs ys
zipWithPadding a _ []     ys     = zip (repeat a) ys
zipWithPadding _ b xs     []     = zip xs (repeat b)

只要有元素,我们就可以简单地将它们压缩.一旦元素用完,我们只需用无限量的padding元素压缩其余列表即可.

As long as there are elements, we can simply zip them. As soon as we run out of elements, we simply zip the remaining list with an infinite list of the padding element.

在您的情况下,您可以将其用作

In your case, you would use this as

zipWithPadding "" "" ["Line1","Line2","Line3"] ["Line4","Line5"]
-- result: [("Line1","Line4"),("Line2","Line5"),("Line3","")]

这篇关于如何压缩不同长度的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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