是否有一个类似于Python的“枚举”函数的Java ?
16lz
2021-01-22
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
更多相关文章
- Python 学习笔记【list的操作方法】
- 使用pip安装tensorflow 0.80,python 使用tensorflow 0.80遇到的问
- 在save方法中创建两个对象
- 堆和索引堆的python实现
- 第四章 当索引不好用时
- 基于Python的XSS测试工具XSStrike使用方法
- 关于Python的属性、参数、方法的解释、区别
- 集成erlang和python的最佳方法
- 如何正确地获取在pysnmp中被捕获的变量的表行索引和命名值?