我希望您能提供一种高效的解决方案来在Julia中删除列表中的空字符串。
这是我的列表:
li = ["one", "two", "three", " ", "four", "five"]
我可以使用for循环来删除空字符串,如下所示:
new_li = []
for i in li
if i == " "
else
push!(new_li, i)
end
end
我认为有更有效的方法来去除空字符串。
我希望您能提供一种高效的解决方案来在Julia中删除列表中的空字符串。
这是我的列表:
li = ["one", "two", "three", " ", "four", "five"]
new_li = []
for i in li
if i == " "
else
push!(new_li, i)
end
end
我认为有更有效的方法来去除空字符串。
new_li = filter((i) -> i != " ", li)
new_li = [i for i in li if i != " "]
过滤器(!=(" "), li)
- Bogumił Kamiński我有一些略长于评论字段的评论:
首先,在构建数组时,永远不要这样开始:
new_li = []
Vector{Any}
,这可能会影响性能。如果您想要初始化一个字符串向量,最好写成:new_li = String[]
其次," "
不是空字符串!看这里:
jl> isempty(" ")
false
""
,没有空格。如果您想要删除空字符串,可以执行以下操作。filter(!isempty, li)
或者,对于原地操作,您可以使用 filter!
:
filter!(!isempty, li)
但实际上你并没有删除空字符串,而是删除了由一个或多个空格组成的字符串,也许还包括真正的空字符串?在这种情况下,你可以使用isspace
和all
。这将删除所有仅为空格的字符串,包括空字符串:
jl> li = ["one", "", "two", "three", " ", "four", " ", "five"];
jl> filter(s->!all(isspace, s), li)
5-element Vector{String}:
"one"
"two"
"three"
"four"
"five"