gpt4 book ai didi

从列表的列表中递归地提取元素

转载 作者:行者123 更新时间:2023-12-04 10:57:56 24 4
gpt4 key购买 nike

我有以下类型的嵌套列表:

我有什么

mylist <- list(
"A",
list(
"B1",
list(
"C_B1",
"w"
),
"B2",
list(
"C_B2",
"x"
),
"B3",
list(
"C_B3_1",
list(
"D_B3_1",
"y"
),
"C_B3_2",
list(
"D_B3_2",
"z"
)
)
)
)

这里列表的名称实际上存储为一个模式,似乎是一个名称后跟一个列表或单个元素。此模式可以扩展任意次数,并且在每个列表中该模式可以重复。

此数据来自 NLP 包中的树结构。这是此结构的示例:https://dl.dropboxusercontent.com/u/61803503/Errors/sample.R

期望的输出

list(
A = list(
B1 = list(
C_B1 = "w"
),
B2 = list(
C_B2 = "x"
),
B3 = list(
C_B3_1 = list(
D_B3_1 = "y"
),
C_B3_2 = list(
D_B3_2 = "z"
)
)
)
)

## $A
## $A$B1
## $A$B1$C_B1
## [1] "w"
##
##
## $A$B2
## $A$B2$C_B2
## [1] "x"
##
##
## $A$B3
## $A$B3$C_B3_1
## $A$B3$C_B3_1$D_B3_1
## [1] "y"
##
##
## $A$B3$C_B3_2
## $A$B3$C_B3_2$D_B3_2
## [1] "z"

注意 不能保证嵌套的程度,只是有一个列表的列表,每个列表的第一个元素是值的名称(第二个元素)在列表中。

最佳答案

我依赖于问题陈述“这里列表的名称实际上存储为每个列表中的第一个元素。”并使用遵循此规则的更正示例。

mylist <- 
list( "A",
list("B1",
list("C_B1",
"w"),
list("B2",
list( "C_B2",
"x")),
list("B3",
list( "C_B3_1",
list( "D_B3_1",
"y"),
list("C_B3_2",
list("D_B3_2",
"z")
)
)
)
)
)

递归遍历列表列表的一种方法是编写一个递归函数,如下所示:

firstEltAsName  <-  function(x){
# if x is not a list, return x
if(!inherits(x,'list'))
return(x)
# recurse on everythin but the first element
out <- lapply(x[-1],firstEltAsName)
# take the names from the first element of the remaining elements.
names(out) <- sapply(x[-1],`[`,1)
# use the first element as the name
return(out)
}
firstEltAsName( mylist)

如果您的示例实际上是正确的,那么您需要:

OddEltsAsNames  <-  function(x){
stopifnot(length(x)%%2 == 0)

# recurse on the even elements
out <- lapply(x[which(seq_along(x)%%2 == 0)],firstEltAsName)

# take the names from the even elements
names(out) <- unlist( x[which(seq_along(x)%%2 == 1)] )

return(out)
}
OddEltsAsNames( mylist)

关于从列表的列表中递归地提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143477/

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