如何将具有已知格式的字符串列表映射到元组列表?
我有一个字符串数组。每个字符串都有 2 个部分,并用空格分隔。看起来像:
x <white space> y
我想把它变成一个元组数组,其中每个元组都有 (x, y)
我怎样才能在 scala 中编写这个?我知道它需要类似的东西:
val results = listOfStrings.collect { str => (str.left, str.right) }
不知道如何将每个 str 分解到所需的左侧和右侧......
I have an array of strings. Each string has 2 parts and is separated by white space. Looks like:
x <white space> y
I want to turn it into an array of Tuples where each tuple has (x, y)
How can I write this in scala? I know it will need something similar to:
val results = listOfStrings.collect { str => (str.left, str.right) }
not sure how i can break up each str to the left and right sides needed...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以利用以下事实:在 Scala 中,正则表达式也是“提取器"。
现在你可以将你的提取器构建成一个看起来很自然的“地图”:
也许对你来说有点大材小用,但如果你的正则表达式变得花哨,确实可以帮助提高可读性。我也喜欢如果给出非法字符串,这种方法会快速失败。
警告,不确定正则表达式是否完全符合您的需要......
You could take advantage of the fact that in Scala, Regular expressions are also "extractors".
Now you can build your extractor into a natural looking "map":
Perhaps overkill for you, but can really help readability if your regex gets fancy. I also like how this approach will fail fast if an illegal string is given.
Warning, not sure if the regex matches exactly what you need...
您可以(假设您想毫无怨言地删除任何不符合模式的字符串):
You could (assuming that you want to drop without complaint any string that doesn't fit the pattern):