如何通过删除 Scala 中的一个元素从列表中获取所有可能的子列表? [英] How to get all sublists possible from a list by removing one element in Scala?

查看:32
本文介绍了如何通过删除 Scala 中的一个元素从列表中获取所有可能的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 List(1,2,3,4) 并希望通过删除一个元素可以获得所有子列表:

I have a list List(1,2,3,4) and want all the sublists obtainable by removing one element:

List(2,3,4)
List(1,3,4)
List(1,2,4)
List(1,2,3)

最简单的方法是什么?

推荐答案

如果您的意思是将列表中的每个位置留在外面",那么:

If you meant "leave each position in the List out", then:

val x = List(1,2,3,2)

x.indices.map(i => x.take(i) ++ x.drop(i+1))
// List(2, 3, 2)      // skipped index 0
// List(1, 3, 2)      // skipped index 1
// List(1, 2, 2)      // skipped index 2
// List(1, 2, 3)      // skipped index 3

如果您的意思是将列表中的每个唯一元素留在外面",那么:

If you meant "leave each unique element in the List out", then:

x.distinct.map(e => x.filter(_ != e))
// List(2, 3, 2)      // filtered out 1s
// List(1, 3)         // filtered out 2s
// List(1, 2, 2)      // filtered out 3s

这篇关于如何通过删除 Scala 中的一个元素从列表中获取所有可能的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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