开发者

Sublists of a list using list comprehension

开发者 https://www.devze.com 2023-02-13 20:18 出处:网络
That simple. I want to generate开发者_如何学Python all sublists of a list using list comprehension.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消