【问题标题】:Python selecting elements in a list by indicesPython通过索引选择列表中的元素
【发布时间】:2014-07-08 22:32:02
【问题描述】:

我在 python 中有一个列表,我想从中获取一组索引并保存为原始列表的子集:

templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]

我想要这个:

   sublist=[[1,    4,    7,                      16,      19,20]]

举个例子。

我无法提前知道列表元素的内容是什么。我所拥有的只是始终相同的索引。

有没有单行的方式来做到这一点?

【问题讨论】:

  • 索引是如何存储的?
  • 什么意思? Python 为列表中的每个元素赋予它自己的索引?
  • 所以告诉我我是否理解正确:你有一个列表,你有一些索引,并且你想提取一个子列表,其中包含这些索引处的列表元素。
  • 是的,先生。它们分散在整个索引中,所以我怀疑 : 运算符不起作用,因为它会连续选择元素
  • 那么您如何知道要选择列表中的哪些索引?

标签: python list indexing set


【解决方案1】:

使用operator.itemgetter

>>> templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
>>> import operator
>>> f = operator.itemgetter(0,3,6,15,18,19)
>>> sublist = [list(f(templist[0]))]
>>> sublist
[[1, 4, 7, 16, 19, 20]]

【讨论】:

    【解决方案2】:

    假设您知道要选择的索引是什么,它的工作原理如下:

    indices = [1, 4, 7, 16, 19, 20]
    templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
    sublist = []
    
    for i in indices:
        sublist.append(templist[0][i])
    

    这也可以用列表推导的形式表达——

    sublist = [templist[0][i] for i in indices]
    

    【讨论】:

      【解决方案3】:

      您可以将列表推导与枚举一起使用:

      indices = [1,2,3]
      sublist = [element for i, element in enumerate(templist) if i in indices]
      

      【讨论】:

        【解决方案4】:

        您可以使用列表推导:

        indices = set([1,2,3])
        sublist = [el for i, el in enumerate(orig_list) if i in indices]
        

        或者您可以将索引存储在 True/False 列表中并使用 itertools.compress

        indices = [True, False, True]
        sublist = itertools.compress(orig_list, indices)
        

        【讨论】:

          【解决方案5】:
           mylist = ['A','B','C','D','E','F']
           idx = [0,1,3]
           [mylist[i] for i in idx]
          

          ['A', 'B', 'D']

          【讨论】:

          • 这根本没有回答OP的问题,这应该是另一个问题吗?
          猜你喜欢
          • 2013-12-03
          • 2018-10-11
          • 1970-01-01
          • 1970-01-01
          • 2019-08-13
          • 1970-01-01
          • 2019-11-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多