【问题标题】:How to add indices to a list?如何将索引添加到列表中?
【发布时间】:2019-07-02 01:18:44
【问题描述】:

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

是否有用于此的内置或模块?

【问题讨论】:

  • 不,这是从 enumerate() 的定义中询问函数本身,而这是询问 enumerate 的函数。

标签: python list indices


【解决方案1】:

您可以使用内置函数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')]

希望对你有帮助。

【讨论】:

  • Enumerate 需要一个参数来更改起始索引值(如果需要)。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    你可以做类似的事情

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

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

    编辑:根据@pault 的建议更新,即使用内置参数

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

    或者干脆

    indexed_list = list(enumerate(your_list, 1))
    

    【讨论】:

    • enumerate 接受一个可选参数,指定开始的 thr 索引
    【解决方案4】:

    Python 中的索引从 0 而不是 1 开始。您可以使用内置的zip() 函数以及itertools 模块中的count() 生成器函数来做您想做的事情。

    如果这是您想要的,还必须将zip() 的结果显式转换为list(这就是为什么我将您的变量名称更改为my_list 以防止它“隐藏”内置-在同名的课堂上——总是这样做是件好事):

    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')]
    

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

    【讨论】:

      【解决方案5】:

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

      >>>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 采用一个可选参数,指定开始的 thr 索引
      【解决方案6】:

      您也可以使用 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。

      【讨论】:

        【解决方案7】:

        使用列表推导和枚举

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

        【讨论】:

          猜你喜欢
          • 2012-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-25
          • 1970-01-01
          • 1970-01-01
          • 2015-05-10
          相关资源
          最近更新 更多