2

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

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

最简单的方法是什么?

4

3 回答 3

3

如果您的意思是“将列表中的每个位置排除在外”,那么:

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

如果您的意思是“将列表中的每个唯一元素排除在外”,那么:

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
于 2012-05-15T15:16:17.457 回答
3
List(1, 2, 3, 4).combinations(3).toList

或者,更一般地说,

list.combinations(list.size - 1) // use the Iterator -- combinations can be huge in size
于 2012-05-15T22:11:40.553 回答
0

我想到了:

val x = List(1,2,3,4)
x.map(i => sizes - i)
于 2012-05-15T15:35:33.543 回答