如何删除子列表 [英] how to remove sub list
本文介绍了如何删除子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从列表中删除所有出现的子列表,例如
How can I remove all occurrences of a sublist from a list, eg
List(1, 2, 3, 4, 5, 6, 7, 4, 8, 9, 10, 5).removeSubList(4, 5)
应删除所有出现的(4,5)(按此顺序!),以便它返回
should remove all occurrences of (4, 5) (in this order!), so it returns
List(1, 2, 3, 6, 7, 4, 8, 9, 10, 5)
推荐答案
使用indexOfSlice
的递归解决方案:
def removeSubList(l: List[Int], sublist: List[Int]): List[Int] = l.indexOfSlice(sublist) match {
case -1 => l
case index => removeSubList(l.patch(index, Nil, sublist.length), sublist)
}
// all of these print List(1 ,2 ,3):
println(removeSubList(List(1,2,3), List(4,5)))
println(removeSubList(List(1,2,3,4,5), List(4,5)))
println(removeSubList(List(4,5,1,2,3), List(4,5)))
println(removeSubList(List(4,5,1,2,4,5,3), List(4,5)))
已编辑:
- (感谢@ corvus_192)恢复为使用
indexOfSlice
版本而不是使用diff
,后者会忽略子列表顺序. - (感谢@The Archetypal Paul)使用
patch
清除了子列表
- (thanks @corvus_192) reverting to using
indexOfSlice
version instead of usingdiff
, which ignores sublist order. - (thanks @The Archetypal Paul) using
patch
for cleaner removal of sublist
这篇关于如何删除子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文