In Python, the enumerate function allows you to iterate over a sequence of (index, value) pairs. For example:

在Python中,枚举函数允许您迭代(索引、值)对的序列。例如:

>>> numbers = ["zero", "one", "two"]
>>> for i, s in enumerate(numbers):
...     print i, s
... 
0 zero
1 one
2 two

Is there any way of doing this in Java?

在Java中有什么方法吗?

10 个解决方案

#1


46

For collections that implement the List interface, you can call the listIterator() method to get a ListIterator. The iterator has (amongst others) two methods - nextIndex(), to get the index; and next(), to get the value (like other iterators).

对于实现列表接口的集合,您可以调用listIterator()方法来获得一个listIterator。迭代器(在其他方法中)有两个方法——nextIndex(),以获得索引;然后,获取值(像其他迭代器一样)。

So a Java equivalent of the Python above might be:

因此,上述Python的Java等效项可能是:

List<String> numbers = Arrays.asList("zero", "one", "two");
ListIterator<String> it = numbers.listIterator();
while (it.hasNext()) {
    System.out.println(it.nextIndex() + " " + it.next());
}

which, like the Python, outputs:

就像Python,输出:

0 zero
1 one
2 two

更多相关文章

  1. Python 学习笔记【list的操作方法】
  2. 使用pip安装tensorflow 0.80,python 使用tensorflow 0.80遇到的问
  3. 在save方法中创建两个对象
  4. 堆和索引堆的python实现
  5. 第四章 当索引不好用时
  6. 基于Python的XSS测试工具XSStrike使用方法
  7. 关于Python的属性、参数、方法的解释、区别
  8. 集成erlang和python的最佳方法
  9. 如何正确地获取在pysnmp中被捕获的变量的表行索引和命名值?

随机推荐

  1. 回调函数在Android监听机制中的体现
  2. 意图过滤器捕获所有共享意图
  3. android未经检查的单选按钮已经检查过
  4. Android中简单活动窗口的切换--Android
  5. Android SDK国内更新
  6. android init进程分析 ueventd — 设备
  7. 将列添加到表时可能发生的冲突
  8. 设置边距更改时,ValueAnimator滞后
  9. Android系统启动流程 -- android
  10. Android 通过Volley 模拟登录教务系统 出