【问题标题】:Python: How to get the nth element from list, where n is from a listPython:如何从列表中获取第 n 个元素,其中 n 来自列表
【发布时间】:2018-12-07 18:41:21
【问题描述】:

所以说我有:

a = ['the dog', 'cat', 'the frog went', '3452', 'empty', 'animal']
b = [0, 2, 4]

如何退货:

c = ['the dog', 'the frog went', 'empty'] ?

即如何从 a 返回第 n 个元素,其中 n 包含在单独的列表中?

【问题讨论】:

  • @d_kennetz 根本不是那个的副本,尽管我同意从标题来看它可能看起来像这样。
  • @AlessandroCosentino 前提是一样的。通过索引访问列表中的项目(仅仅因为索引在另一个列表中)并没有太大变化。

标签: python python-2.7 list


【解决方案1】:

使用列表推导,只需:

c = [a[x] for x in b]

【讨论】:

    【解决方案2】:

    另一种方法是:

    map(a.__getitem__, b)
    

    【讨论】:

    • 善用地图。也可以转换为列表,这将在 python2 和 3 中工作
    【解决方案3】:

    另一种解决方案:如果您愿意使用 numpy (import numpy as np),您可以使用其精美的索引功能 (à la Matlab),即在一行中:

    c = list(np.array(a)[b])
    

    【讨论】:

      【解决方案4】:

      其他选项,列表理解迭代 a 代替(效率较低):

      [ e for i, e in enumerate(a) if i in b ]
      
      #=> ['the dog', 'the frog went', 'empty']
      

      lambda

      map( lambda x: a[x], b )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 2019-09-05
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多