简体   繁体   中英

How can I remove every the first number, last number and middle number in a list?

So I'm trying to write a function chosen(lst:list[int]) -> list[int] that returns a list that contains all elements of lst but the front element, the middle element, and the last element. You may assume that the length of lst is greater than 3 and always odd.

For example, chosen([9,3,5,7,1]) returns [3,7] and chosen([0,2,7,0,0,5,0,0,0]) returns [2,7,0,5,0,0]. Here is my code so far....

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

What should I change to make sure this works??

One approach:

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)

Output

[3, 7]

The idea is to first select the indices to remove and then simply filter out the elements at those indices.

Note that remove , actually removes the first item from the list whose value is equal to x. So your approach wont work with duplicated values.

Remove from the last otherwise indices won't be correct

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]

You can use tuple unpacking to remove the first and the last item. Then pop the middle element.

def chosen(lst):
    _, *out, _ = lst
    out.pop(len(out)//2)
    return out

chosen([9,3,5,7,1])
# [3, 7]

You can use list.pop(index) function to remove element by providing index value.

NOte you need to provide index from the largest to lowest, as once you remove a element, list got reindexed, and element index changes

# 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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM