【问题标题】:How to to delete multiple items not in a given array如何删除不在给定数组中的多个项目
【发布时间】:2018-08-06 23:03:55
【问题描述】:

我有这个代码:

delIndex = []
for a in range(0, 10):
    if a not in found_index and len(found_index) > 0:
        delIndex.append(a)
for index in sorted(delIndex, reverse=True):
    del faces[index]

此代码删除不在数组found_index中的项目 有没有办法通过使用完成这项工作或其他事情的方法来简化代码?

【问题讨论】:

  • 不确定您到底想做什么。你问:“有没有办法通过使用完成这项工作或其他事情的方法来简化?”在这种情况下,什么是“另一件事”?您要简化上述代码的哪一部分?另外,faces 字典来自哪里?什么是“这份工作”?
  • 为什么是“numpy”标签?
  • 你能保证数组是唯一的吗?如果你想从[1,2,3,1] 中删除1,你期望什么?
  • 检查这些链接:link 1link 2他们可能会帮助您获取信息!
  • 欢迎来到 SO!请提供 minimal reproducible example,因为您的问题目前尚不清楚。

标签: python python-3.x numpy


【解决方案1】:

你可以使用 set

试试这样:-

a = [6,8,10] #to be deleted
b = list(range(11)) #compare list
ls= set(b) ^ set(a)
print(ls)#your output

【讨论】:

    【解决方案2】:

    如果我理解正确,您想从列表中过滤掉所有元素,这些元素包含在第二个列表中:

    [element for element in faces if element not in found_index]
    

    【讨论】:

      【解决方案3】:

      您可以将代码简化为:

      delIndex = sorted([a for a in range(0, 10) if a not in found_index], reverse=True)  
      for index in delIndex:
          del faces[index]
      

      如果您使用列表facesfound_index 的更多详细信息和示例更新您的答案(例如,它是否唯一,是否包含重复项),以及您为什么进行反向排序,我可能会更新此答案。

      【讨论】:

        【解决方案4】:

        我不明白什么是面,所以我只解释如何通过两组元素的差异来删除元素。在您的情况下 found_index[a for a in range(0, 10)] 。使用python内置的set,以及区别方法——documentation here

        values_to_remove = set([a for a in range(0, 10)])
        found_index = set(found_index)
        new_itemS = found_index.difference(values_to_remove)
        # you can write also new_itemS = found_index - values_to_remove     new set with elements in found_index but not in values_to_remove
        

        【讨论】:

          【解决方案5】:

          我想你正在寻找How to remove specific element in an array using python

          如果这就是您要找的,请告诉我。或者,向我们提供输入和输出示例,以便我们使用您的代码。

          更新:添加代码示例。

          代码示例:

          #!/usr/bin/env python
          
          mainArray = [1, 2, 3, 4, 5, 6]
          arrayRemove = [1, 3, 6]
          
          mainArray = [e for e in mainArray if e not in arrayRemove]
          print(mainArray)
          

          【讨论】:

          • 这属于评论,不是答案。
          • 您好@brunodesthuilliers,您知道在投票否决新用户之前,它试图免费帮助他的时间,最好教一下这个论坛的工作原理。或者,您最终会迫使人们放弃花时间提供帮助。 (请记住,下一个用户您也会这样做)
          • 因为它被记录在案最好提供一个链接,以防有人不知道在哪里阅读它。最重要的是,学习如何训练以创造更好的开发人员,而不是训练如何出错。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-19
          • 1970-01-01
          • 1970-01-01
          • 2020-11-16
          • 1970-01-01
          相关资源
          最近更新 更多