如何将索引添加到列表中?

How to add indices to a list?

比如我有一个list = ['a', 'b', 'c'].
我想要的是一个列表 indexed(list) == [(1, 'a'), (2, 'b'), (3, 'c)].

是否有内置或模块?

您可以通过执行以下操作来枚举它,

for i,n in enumerate(list):
# where i is the index and n is the value of the list

您可以使用 built-in 函数 enumerate 来实现。

In [1]: a = ['a', 'b', 'c']

In [2]: b = [(idx, item) for idx,item in enumerate(a)]

In [3]: b
Out[3]: [(0, 'a'), (1, 'b'), (2, 'c')]

注意:默认索引以 0 开头,但您可以尝试添加 start=1 来配置它,例如

In [4]: c = [(idx, item) for idx,item in enumerate(a, start=1)]

In [5]: c
Out[5]: [(1, 'a'), (2, 'b'), (3, 'c')]

希望对您有所帮助。

你可以做类似

indexed_list = [(i + 1, elem) for i, elem in enumerate(your_list)]

我假设您需要索引从 1 开始。否则您可以直接对 enumerate 结果进行列表推导,而无需向索引添加 1。

编辑:根据@pault 的建议更新,即使用 built-in 参数

indexed_list = [indexed for indexed in enumerate(your_list, 1)]

或者干脆

indexed_list = list(enumerate(your_list, 1))

下面的代码就是你想要的:

>>>l = ['a', 'b', 'c']
>>>indl = [(i + 1, val) for i, val in enumerate(l)]
>>> indl
[(1, 'a'), (2, 'b'), (3, 'c')]

编辑:根据@pault的建议,代码修改如下:

>>> yourList = ['a', 'b', 'c']
>>> listInd = [(i, val) for i, val in enumerate(yourList, 1)]
>>> listInd
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> 

你可以使用 enumerate,它也是这个的起始参数:

l = ['a', 'b', 'c']
indexed_list = list(enumerate(l, 1))

至于一个叫做 indexed 的函数,你可以做一个

注意! 切勿替换内置关键字! list列表就是其中之一

>>> def indexed(l, start=1):
    ...    return list(enumerate(l, start))
>>> l = ['a', 'b', 'c']
>>> indexed(l)
[(1, 'a'), (2, 'b'), (3, 'c)]

这默认为起始值 1。

Python 中的索引从 0 开始,而不是 1。您可以使用 built-in zip() function along with the count() generator function in the itertools 模块做您想做的事。

还需要将 zip() 的结果显式转换为 list,如果这是您想要的(这就是为什么我将变量名称更改为 my_list 以防止它来自 "hiding" built-in class 同名 — always 做的一件好事:

from itertools import count

my_list = ['a', 'b', 'c']

indexed_my_list = list(zip(count(), my_list))
print(indexed_my_list)  # -> [(0, 'a'), (1, 'b'), (2, 'c')]

不清楚您为什么需要这样做,因为您可以使用 built-in enumerate() 函数在需要时获取索引,如许多其他答案中所示。

使用列表理解和枚举

[(i,l) for i,l in enumerate(list)]