【问题标题】:How can I remove every the first number, last number and middle number in a list?如何删除列表中的每个第一个数字、最后一个数字和中间数字?
【发布时间】:2022-01-05 04:11:16
【问题描述】:

所以我正在尝试编写一个函数 selected(lst:list[int]) -> list[int] 返回一个列表,该列表包含 lst 的所有元素,但前面元素、中间元素和最后一个元素.你可以假设 lst 的长度大于 3 并且总是奇数。

例如,choice([9,3,5,7,1]) 返回 [3,7] 并且 selected([0,2,7,0,0,5,0,0,0]) 返回[2,7,0,5,0,0]。 到目前为止,这是我的代码....

def first(lst: list) -> list:
    if len(lst)%2 == 0:
        lst.remove(lst[0])
        lst.remove(lst[len(lst)//2])
        lst.remove(lst[-1])
    else:
        lst.remove(lst[0])
        lst.remove(lst[(len(lst) // 2)-1])
        lst.remove(lst[-1])
    return lst

我应该改变什么以确保它有效??

【问题讨论】:

  • 您是否需要修改现有的列表,或者您可以复制一份吗?

标签: python list function tuples


【解决方案1】:

从最后一个中删除,否则索引将不正确

l = [9,3,5,7,1]
indices_to_be_poped = [0, len(l)//2, len(l)-1]

for i in indices_to_be_poped[::-1]:
    l.pop(i)
    
    
print(l) #[3, 7]

【讨论】:

    【解决方案2】:

    一种方法:

    def chosen(lst):
        indices = [0, len(lst) // 2, len(lst) - 1]
        return [v for i, v in enumerate(lst) if i not in indices]
    
    
    res = chosen([9,3,5,7,1])
    print(res)
    

    输出

    [3, 7]
    

    这个想法是首先选择要删除的索引,然后简单地过滤掉那些索引处的元素。

    请注意,remove 实际上从列表中删除了值等于 x 的第一项。因此,您的方法不适用于重复值。

    【讨论】:

      【解决方案3】:

      您可以使用tuple unpacking 删除第一项和最后一项。然后弹出中间元素。

      def chosen(lst):
          _, *out, _ = lst
          out.pop(len(out)//2)
          return out
      
      chosen([9,3,5,7,1])
      # [3, 7]
      

      【讨论】:

        【解决方案4】:

        您可以使用list.pop(index) 函数通过提供索引值来删除元素。

        请注意,您需要提供从最大到最低的索引,因为一旦您删除了一个元素,列表就会重新索引,并且元素索引会发生变化

        # your code goes here
        def chosen(array: list):
            length = len(array)
            remove = [length-1, length//2, 0]
            
            for i in remove:
                array.pop(i)
            return array
        
        assert chosen([0,2,7,0,0,5,0,0,0]) == [2,7,0,5,0,0] 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 2011-04-11
          • 1970-01-01
          • 1970-01-01
          • 2022-12-18
          相关资源
          最近更新 更多