That simple. I want to generate开发者_如何学Python all sublists of a list using list comprehension.
i.e: getSublist [1,2,3] is [[1], [2], [3], [1,2], [1,3], [2, 3], [1,2,3]]
Thanks
This is already implemented as Data.List.subsequences
, but if you want to define it yourself (for learning purposes), you can do it like this:
You can't do it with only list comprehensions, but with some recursion it looks like this:
sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs
Read: The only sublist of the empty list is the empty list. The sublists of x:xs
(i.e. the list with the head x
and the tail xs
) are all of the sublists of xs
as well as each of the sublists of xs
with x
prepended to them.
精彩评论