python - 创建一个删除列表中奇数倍数的函数

标签 python

修订问题之一涉及通过删除列表中所有奇数且 x 的倍数的整数来修改原始列表。

def remove_odd_multiples(numbers_list, multiple_of):
    for ele in numbers_list:
        if (ele%2) != 0 and (ele % multiple_of) == 0:
            numbers_list.remove(ele)
    
    return numbers_list

输出:

numbers_list = [1, 5, 23, 3, 6, 17, 9, 18]
print("Before:", numbers_list)
remove_odd_multiples(numbers_list, 3)
print("After:", numbers_list)

Before: [1, 5, 23, 3, 6, 17, 9, 18]
After: [1, 5, 23, 6, 17, 18]

它确实有效,但是将代码输入到 coderunner 中时,我的代码未通过一些未显示的隐藏检查。我解决这个问题的方法是错误的吗?我应该使用 pop 而不是 .remove 吗?

最佳答案

您可以使用列表理解来返回包含结果的新列表,而不是在迭代时删除。

def remove_odd_multiples(numbers_list, multiple_of):
    return [x for x in numbers_list if x % 2 == 0 or x % multiple_of != 0]

就地修改列表:

def remove_odd_multiples(numbers_list, multiple_of):
    numbers_list[:] = [x for x in numbers_list if x % 2 == 0 or x % multiple_of != 0]

删除元素时向后循环还可以确保未处理的元素不会移动。

def remove_odd_multiples(numbers_list, multiple_of):
    for i in range(len(numbers_list) - 1, -1, -1):
        if (numbers_list[i]%2) != 0 and (numbers_list[i] % multiple_of) == 0:
            del numbers_list[i]

关于python - 创建一个删除列表中奇数倍数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67410902/

相关文章:

python - 没有这样的表: wagtailcore_site

python - 在列表理解中包含 'and' 命令

python - 使用 redis 和 celery 向所有工作人员广播任务

python - 将相似的模式合并为单一的共识模式

python - 安排 pyspark 笔记本

python - 根据特定索引处的值从元组列表中删除重复项

python - Django collectstatic 不覆盖生产文件

python - django 运行 unittest 失败,而我的一个名为 "apps"的应用程序,但 "runserver"有效

python - 查找两个数据集之间对应的 bin

python - 在 Python 中遍历子目录并保存到同一子目录