【问题标题】:How to take out elements knowing their indexes如何取出知道索引的元素
【发布时间】:2018-09-05 06:16:03
【问题描述】:

我的程序有点麻烦,我想从一个列表中取出一些知道它们的索引的元素,然后将这些元素添加到另一个列表中......例如:

a= ['dog','cat','house','car']
c=[]
#list with the indexes:
b=[0,2]

所以我想取出索引为“0”和“2”的a的元素并将它们添加到c列表中。

【问题讨论】:

  • c=[a[i] for i in b]
  • 这些信息(del list1[2];,list1.append('a'))可能对你有帮助,你可以自己google一下使用。

标签: python list indexing


【解决方案1】:

cmets 也很有帮助,但这里简明扼要: 遍历 b 中的元素,从 a 中取出索引并附加到 c 中。

for i in b:
    c.append(a.pop(i))

可能有一种方法可以通过列表理解来做到这一点,但我还不知道。 希望这会有所帮助!

【讨论】:

  • 如果你想使用列表推导:c = [a.pop(i) for i in b]
  • @t.m.adam 感谢您的信息!我还在学习,但我猜可能是这样的。
  • 不客气!如果您愿意,您可以将其包含在您的答案中,尽管这很好。
【解决方案2】:

从列表中删除一个元素:

a.remove(0)

或者你可以这样做

del a[0]

将元素添加到列表中:

c.insert(0,'dog')
c.insert(1,'house')

【讨论】:

    【解决方案3】:

    遍历您的索引数组,在索引处弹出项目并将其附加到您的新数组中。

    i = 0
    while i < len(b):
    c.append(a.pop(b[i]))
    i+=1
    

    【讨论】:

      【解决方案4】:

      您可以将第一个数组转换为 numpy 数组。然后你可以简单地从 b 传递索引。

      import numpy as np
      a = np.array(['dog','cat','house','car'])
      b = [0,2]
      c = a[b]
      
      print(c) 
      >>> array(['dog', 'house'],
        dtype='<U5')
      

      要将 c 转换回列表,只需使用 .tolist()

      print(c.tolist())
      >>> ['dog', 'house']
      

      【讨论】:

        【解决方案5】:

        试试这个小代码:

        a= ['dog','cat','house','car']
        b=[0,2]
        
        print(list(map(lambda x:a[x],b)))
        

        输出:

        ['dog', 'house']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-21
          • 2012-09-11
          • 1970-01-01
          • 2021-11-05
          • 2013-08-18
          • 2011-10-13
          • 2013-04-25
          • 1970-01-01
          相关资源
          最近更新 更多