list(c(1,2), c(2,3), c(3,4))
返回list(c(1,2,3,4))
的条件意味着我们必须遍历列表,直到它停止更改.
我们可以使用递归函数,该函数在满足该条件时停止调用自身.
create_merged_list <- function(l, check_finished_list = NULL) {
new_l <- unique(lapply(seq(l), \(i) merge_elements(l, i)))
if (identical(check_finished_list, new_l)) {
return(new_l)
}
create_merged_list(new_l, l)
}
这次调用的主要函数是merge_elements()
,它迭代列表的每个元素,将其与与其共享值的其他元素合并,并返回一个新的列表.
merge_elements <- function(l, i) {
l_compare <- l[-i]
el <- l[[i]]
match_vals <- which(outer(el, unlist(l_compare), \(x, y) x == y), arr.ind = TRUE)[, "col"]
if (!length(match_vals)) {
return(el)
}
l_breaks <- cumsum(lengths(l_compare))
l_match_idx <- vapply(match_vals, \(x) min(which(x <= l_breaks)), integer(1))
new_el <- sort(unique(c(el, unlist(l_compare[l_match_idx]))))
new_el
}
输出
create_merged_list(int_list)
# [[1]]
# [1] 1 15
# [[2]]
# [1] 3 4 19 28 30
# [[3]]
# [1] 2 16
# [[4]]
# [1] 5 21
# [[5]]
# [1] 17
identical(create_merged_list(int_list), int_list_merged)
# [1] TRUE