如何在 Julia 中对多个值使用“endswith()”?

How to use `endswith()` against multiple values in Julia?

提问人:Sudoh 提问时间:7/24/2022 最后编辑:Sudoh 更新时间:7/25/2022 访问量:146

问:

我有一个,我想在它上面使用,但针对多个值。stringendswith()

我的第一个猜测是用元组来尝试:

# {string}

suffixes = ({multiple suffixes here})

endswith(i,extensions)

这生成了错误消息:

MethodError: no method matching endswith(::String, ::Tuple{String, String})

所以,我去 Julia 文档中寻找官方文档,但他们只谈论单字符串比较。

我确实在一个非官方网站上找到了这个,上面写着:

如果第二个参数是向量或字符集,则测试的最后一个字符是否属于该集。string

这并不完全适用。

我尝试了以下变体:

endswith(i,extensions[:])

产生与以前相同的错误MethodError: no method matching endswith(::String, ::Tuple{String, String})

列表的变体:

# {string}

suffixes = [{multiple suffixes here}]

endswith(i,extensions)

仅将错误消息从元组更改为向量

MethodError: no method matching endswith(::String, ::Vector{String})

或提供索引

# {string}

suffixes = [{multiple suffixes here}]

endswith(i,extensions[:])

同样的错误

MethodError: no method matching endswith(::String, ::Vector{String})

我尝试了元组和向量,但也没有用。endswith(i,extensions[1:length(extensions)])

有人熟悉吗?

朱莉娅

评论

1赞 phipsgabler 7/25/2022
目前尚不完全清楚您是否需要结果列表(每个后缀为 true/false),或者确定任何后缀是否匹配。
0赞 Sudoh 7/25/2022
我是否想要一个布尔数组或满足条件的列表子集?后者是我想要的。因此,对于可以具有任何后缀的后缀,我想针对我选择的列表进行测试。例如,test against 和 since is 在列表中,字符串通过了测试。stringstringsuffixesfile.pep[".pep",".txt",".xlsx'].pepfile.pep

答:

2赞 Bogumił Kamiński 7/24/2022 #1

您可能需要以下内容:

julia> endswith.("abcd", ["d", "c", "cd", "dc"])
4-element BitVector:
 1
 0
 1
 0

请注意 .此操作通过集合(在本例中为后缀向量)广播函数。有关详细信息,请参阅此处.endswith

评论

1赞 Sudoh 7/24/2022
是的,就是这样。这在 for 循环中失败了,知道我在哪里可以查看文档吗?在 for 循环中使用它时的错误是non-boolean (BitVector) used in boolean context
2赞 Bogumił Kamiński 7/24/2022
不清楚你说的“这在for循环中失败”是什么意思。你能分享一下代码吗?
1赞 Sudoh 7/24/2022
对不起,pastery.net/cbqthg 不得不在这里做糊状物。
2赞 Bogumił Kamiński 7/24/2022
在代码中,更改为push!(my_list,i)
1赞 Sudoh 7/24/2022
这是一个语法错误,但这不是抛出错误。我将代码更改为此 pastery.net/qkkbsx,但仍然收到相同的错误。我将在 for 循环中使用,因为这不会导致布尔问题。抱歉,我今天早上开始使用 Julia,并试图解决来自 python 的学习曲线。TypeError: non-boolean (BitVector) used in boolean contextendswith(i,r".item_one|item_two|...")
4赞 Sudoh 7/24/2022 #2

似乎以下情况也是可能的:

endswith("{string}",r"item_one|item-two|item_three|item_four") # items being what I want to check the string for.

如果我的项目是动态的,我想我可以使用 f 字符串来创建 r“{item_list_here}”

评论

2赞 phipsgabler 7/25/2022
动态构造将是 。Regex(join(suffixes, "|"))