[英]Take every item in list that starts with x and put it in a new list - Rego
list:= ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]列表:= [“a:aqsdf”、“a:asdf”、“b:gfs”、“b:sdf”、“a:adfd”、“b:asdfd”]
I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]我希望新列表仅包含以 'a' 开头的项目:["a:aqsdf", "a:asdf", "a:adfd"]
I've tried working with sets with no success.我尝试过使用套装但没有成功。 This would be a breeze in python but can't seem to wrap my head around rego.
在 python 中这将是一件轻而易举的事,但我似乎无法理解 rego。 I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)
我可以把它变成一个集合,但不知道如何挤进 if 语句(startswith(list[_], "a") == true)
One way to do this is with an array comprehension and the startswith
builtin function:一种方法是使用数组理解和内置
startswith
的开头:
[ x | x := list[_]; startswith(x, "a")]
Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h游乐场示例: https://play.openpolicyagent.org/p/8mQYYvUL2h
This is essentially saying to define a new array containing the value of x
if the rule body is true.这本质上是说如果规则主体为真,则定义一个包含
x
值的新数组。 The rule body for the comprehension is in turn iterating over all indicies of list
for values of x
, and will be true when the value of x
starts with "a"
.理解的规则体依次迭代
list
的所有索引以获取x
的值,并且当x
的值以"a"
开头时为真。
References:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.