如何向列表的每个元素添加递增计数器
我有:
scala> val alphaList = List("a", "b")
alphaList: List[java.lang.String] = List(a, b)
并且我想要一个元组列表,例如:
List((a,1),(b,2))
通常在Java中我会做类似的事情:
List alphaList = new ArrayList<String>()
alphaList.add("a");alphaList.add("b");
List newList = new ArrayList<String>();
for ( int i = 0; ii < alphaList.size(); i++ )
newList.add(alphaList[i] + i);
我想要得到的是,如何获得一个可以在处理列表时使用的递增变量?
I have:
scala> val alphaList = List("a", "b")
alphaList: List[java.lang.String] = List(a, b)
and I'd like a list of tuples like:
List((a,1),(b,2))
Normally in Java I'd do something like:
List alphaList = new ArrayList<String>()
alphaList.add("a");alphaList.add("b");
List newList = new ArrayList<String>();
for ( int i = 0; ii < alphaList.size(); i++ )
newList.add(alphaList[i] + i);
What I'm trying to get at, is how do I get an incrementing variable that I can use while processing a List?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样...
测试:
How about...
Test:
zipWithIndex
将每个元素替换为其自身及其索引(从 0 开始)的元组。map
匹配该元组,并创建一个索引加 1 的新元组,以便从 1 开始,而不是从 0 开始。The
zipWithIndex
replaces each element with a tuple of itself and its index (starting from 0). Themap
matches the tuple, and creates a new tuple with the index incremented by 1, so that you start from 1, instead of 0.作为 Axel22 答案的替代方案,这很好:
As an alternative to Axel22's answer, which is fine :