gpt4 book ai didi

递归列表

转载 作者:行者123 更新时间:2023-12-04 12:02:54 27 4
gpt4 key购买 nike

考虑以下代码:

b <- list(u=5,v=12)
c <- list(w=13)
a <- list(b,c)

因此,a实际上是列表列表。当我调用 a$ba$c时,为什么返回 NULL?同样,如果我调用 a$ua$va$w,则返回 NULL

以下内容之间也有区别:
c(list(a=1,b=2,c=list(d=5,e=9))) 


c(list(a=1,b=2,c=list(d=5,e=9)), recursive=T)

最佳答案

$索引运算符按名称对列表进行索引。如果要从未命名列表a中获取第一个元素,则需要a[[1]]

您可以创建一个函数,如果未指定名称,则自动添加名称,类似于data.frame的工作方式(此版本为全有或全无-如果命名了某些参数,则不会命名其余未命名的参数)。

nlist <- function(...) {
L <- list(...)
if (!is.null(names(L))) return(L)
n <- lapply(match.call(),deparse)[-1]
setNames(L,n)
}

b <- c <- d <- 1

nlist(b,c,d)
nlist(d=b,b=c,c=d)

对于第二个问题,答案是"is"。你尝试过了吗?
L <- list(a=1,b=2,c=list(d=5,e=9))
str(c(L))
## List of 3
## $ a: num 1
## $ b: num 2
## $ c:List of 2
## ..$ d: num 5
## ..$ e: num 9
str(c(L,recursive=TRUE))
## Named num [1:4] 1 2 5 9
## - attr(*, "names")= chr [1:4] "a" "b" "c.d" "c.e"

第一个是包含两个数字值和一个列表的列表,第二个已被展平为命名的数字矢量。

关于递归列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14123761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com