将列表拆分成可能的元组列表 [英] Splitting list into a list of possible tuples
本文介绍了将列表拆分成可能的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将列表分成所有可能的元组列表,但我不确定如何去做。
例如
对[cat,dog,mouse]
会导致
我能够形成前两个,但是我不确定如何获得剩下的。 [(cat,dog),(cat ,鼠标),(狗,猫),(狗,鼠标),(鼠标,猫),(鼠标,狗)]
pairs :: [a] - > [(a,a)]
对(x:xs)= [(m,n)| m < - [x],n < - xs]
解决方案
您可以使用列表理解:
allpairs :: Eq a => [a] - > [(a,a)]
allpairs xs = [(x1,x2)| x1 < - xs,x2 < - xs,x1 / = x2]
I need to split a list into a list of all possible tuples, but I'm unsure of how to do so.
For example
pairs ["cat","dog","mouse"]
should result in
[("cat","dog"), ("cat","mouse"), ("dog","cat"), ("dog","mouse"), ("mouse","cat"), ("mouse","dog")]
I was able to form the first two, but am unsure of how to get the rest.
Here's what I have so far:
pairs :: [a] -> [(a,a)]
pairs (x:xs) = [(m,n) | m <- [x], n <- xs]
解决方案
You can use a list comprehension:
allpairs :: Eq a => [a] -> [(a,a)]
allpairs xs = [ (x1,x2) | x1 <- xs, x2 <- xs, x1 /= x2 ]
这篇关于将列表拆分成可能的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文