我有以下HTML输入列表。列表具有嵌套结构-
input1
)。name
,attribs
,children
children
,它是长度为2的列表-第一个元素包含有关输入标签的信息,第二个元素包含有关输入类型的信息。由于需要输入标签,因此需要为每个输入提取此列表的第一个元素。 列表:
library(purrr)
inputs = list(
input1 = list(
name = 'div',
attribs = list(class = 'form-group'),
children = list(list(name = 'label',
attribs = list(`for` = 'email'),
children = list('Email')),
list(
list(name = 'input',
attribs = list(id = 'email', type = 'text'),
children = list()))
)))
str(inputs)
List of 1
$ input1:List of 3
..$ name : chr "div"
..$ attribs :List of 1
.. ..$ class: chr "form-group"
..$ children:List of 2
.. ..$ :List of 3
.. .. ..$ name : chr "label"
.. .. ..$ attribs :List of 1
.. .. .. ..$ for: chr "email"
.. .. ..$ children:List of 1
.. .. .. ..$ : chr "Email"
.. ..$ :List of 1
.. .. ..$ :List of 3
.. .. .. ..$ name : chr "input"
.. .. .. ..$ attribs :List of 2
.. .. .. .. ..$ id : chr "email"
.. .. .. .. ..$ type: chr "text"
.. .. .. ..$ children: list()
我可以使用keep()
和has_element
来做到这一点:
label = input %>%
map_depth(2, ~keep(., ~has_element(., 'label'))) %>%
map('children') %>%
flatten %>%
map('children') %>%
flatten
输出:
str(label)
List of 1
$ input1: chr "Email"
当我浏览purrr
帮助页面时,keep
似乎是我所追求的功能,但是我仍然必须两次使用map
和flatten
才能获得标签,看起来很笨拙。所以我想知道是否有更直接的方法来实现相同的输出?我对解决方案的兴趣不大,因为我对使用此类嵌套列表背后的想法很感兴趣。
答案 0 :(得分:1)
如果每个输入都具有相同的结构,则不需要EncryptionAlgorithm.AES192
,它用于删除不满足某些条件的列表元素。相反,您可以像这样通过keep
进行映射。当然,此方法将删除与每个输入相关的所有其他数据。如果最终目标是“重组”,即采用平面结构获取每个输入的所有信息,则可能需要做一些不同的事情。
pluck
由reprex package(v0.3.0)于2019-06-14创建
答案 1 :(得分:0)
尝试:
map(inputs, "children") %>% map_depth(2, "children")
输出:
$input1
$input1[[1]]
$input1[[1]][[1]]
[1] "Email"
$input1[[2]]
NULL