当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Elixir Enum.with_index用法及代码示例

Elixir语言中 Enum.with_index 相关用法介绍如下。

用法:

with_index(enumerable, fun_or_offset \\ 0)
@spec with_index(t(), integer()) :: [{term(), integer()}]
@spec with_index(t(), (element(), index() -> value)) :: [value] when value: any()

返回 enumerable ,每个元素都包装在一个元组中,旁边是它的索引。

可以接收一个函数或一个整数偏移量。

如果给出offset,它将从给定的偏移量而不是从零开始索引。

如果给出function,它将通过为每个元素和可枚举的索引(从零开始)调用函数来索引。

例子

iex> Enum.with_index([:a, :b, :c])
[a: 0, b: 1, c: 2]

iex> Enum.with_index([:a, :b, :c], 3)
[a: 3, b: 4, c: 5]

iex> Enum.with_index([:a, :b, :c], fn element, index -> {index, element} end)
[{0, :a}, {1, :b}, {2, :c}]

相关用法


注:本文由纯净天空筛选整理自elixir-lang.org大神的英文原创作品 Enum.with_index(enumerable, fun_or_offset \\ 0)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。