删除号码列表中最后一个偶数


# Task_5
def delete_last_even(num_list):
"""Removes the last even number from a list of numbers.
Args:
num_list (list): List of numbers to be checked.
Returns:
list: List of numbers with the last even number
removed.
"""
if len(num_list) % 2 == 0:
num_list.pop()
else:
return num_list
delete_last_even([7, 65, 1337, 8, -2, 24, 6, 67, 54, 36, 25, 1, 42, 9, 138, 4356, 6])

让我知道我解释错了什么。我的if语句询问变量(num_list)中的数字是否为偶数,然后调用.pop()函数从列表中删除最后一项。最后,返回num_list。当我运行这个时,我得到,None。

看来您误解了需求,它要求您删除last even number,但您已经检查了列表中的len。前面评论中的PO已经回答了你为什么要返回None的问题。

这里只是另一种接近它的方法,并将性能与其他PO进行比较,以显示差异。

def delete_last_even(nums):
for i, num in enumerate(reversed(nums)):  # to reverse the contents of a list object in-place.  You won't be creating a new list. 
if num % 2 == 0:
nums.pop(~i)     # directly remove the num by ~i, aka, backward idx

break
return nums

输出:

A = [1, 2, 3, 5, 6, 7]
delete_last_even(A) 
# [1, 2, 3, 5, 7]
delete_last_even([6, 1, 2, 3, 5, 6, 7])
#  [6, 1, 2, 3, 5, 7]            *

性能比较:first function is 51% faster than 2nd one..

如果输入的大小很大,这可能是一个合理的问题。


In [1]: nums = [1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 21]
In [2]: def delete_last_even(nums):
...:     # same as theabove code
...:
In [3]: def delete_last_even2(nums):
...:     for idx, n in enumerate(nums[::-1]):
...:         if n % 2 == 0:
...:             nums.pop(idx)
...:             break
...:     return nums
...:
In [4]: %timeit delete_last_even(nums)
761 ns ± 54.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [5]: %timeit delete_last_even2(nums)
1.2 µs ± 145 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

首先必须找到最后一个偶数字符的索引。为此,您可以枚举反向列表num_list[::-1]。然后,您必须从列表中弹出它,您可以返回列表或打印更新后的列表,如下所示。注意,这里的枚举是为了找到列表中偶数字母的索引。

def delete_last_even(num_list):
for index, number in enumerate(num_list[::-1]):
if number % 2 == 0 :
num_list.pop(len(num_list)-1-index)
return num_list
return num_list

您可以检查测试用例的输出,如下所示

print(delete_last_even([7, 65, 1337, 8, -2, 24, 6, 67, 54, 36, 25, 1, 42, 9, 138, 4356, 6]))

如果你想了解更多关于枚举函数的信息,可以参考文档

请注意,当长度可以被2整除时,您没有返回对象。

此外,如果长度为偶数,则删除列表的最后一个元素。从你的任务请求中,我不清楚这是你想要的,因为"删除最后一个偶数"。也可能意味着找到最后一个偶数元素并删除它。所以[0,1,2]会映射到[0,1],[2,1,3]会映射到[1,3]而[3,1]只会映射到自己如果你想找到列表中最后一个偶数元素

for index,num in enumerate(num_list[::-1]) :
if num%2==0:
num_list.pop(len(num_list)-1-index)
break
return num_list

最新更新