Python-在列表上迭代

Python-在列表上迭代,python,python-3.x,loops,for-loop,iterated-function,Python,Python 3.x,Loops,For Loop,Iterated Function,我希望我的代码的第二个函数修改我的第一个函数生成的新列表 如果我理解正确,在这种情况下,给出一个列表作为参数将给出原始列表我的_列表 那么代码删除1和5,然后添加6,但不是7 my_list = [1, 2, 3, 4, 5] def add_item_to_list(ordered_list): # Appends new item to end of list which is the (last item + 1) ordered_list.append(my_list[

我希望我的代码的第二个函数修改我的第一个函数生成的新列表

如果我理解正确,在这种情况下,给出一个列表作为参数将给出原始列表我的_列表

那么代码删除1和5,然后添加6,但不是7

my_list = [1, 2, 3, 4, 5]

def add_item_to_list(ordered_list):
    # Appends new item to end of list which is the (last item + 1)
    ordered_list.append(my_list[-1] + 1)

def remove_items_from_list(ordered_list, items_to_remove):
    # Removes all values, found in items_to_remove list, from my_list
    for items_to_remove in ordered_list:
        ordered_list.remove(items_to_remove)

if __name__ == '__main__':
    print(my_list)
    add_item_to_list(my_list)
    add_item_to_list(my_list)
    add_item_to_list(my_list)
    print(my_list)
    remove_items_from_list(my_list, [1,5,6])
    print(my_list)
产量

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 4, 6, 8]
而不是通缉

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 7, 8]     
感谢您并对您在“从列表中删除项目”函数中遇到的基本问题表示歉意,您正在迭代错误的列表。您应该像下面这样遍历items_to_remove列表中的每个项目:

def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list

    for item in items_to_remove:
        ordered_list.remove(item) 
这将遍历删除列表中的每个项目,并将其从您订购的列表中删除。

从列表中删除项目功能中存在错误。为了实现您的目标,it部门应该:

def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
    for item in items_to_remove:
        ordered_list.remove(item)

作为旁注,您的代码在函数定义之前有不正确的空行数。函数前应为两个空行,函数内不得有多个空行。它目前似乎没有影响代码,但会使代码更难阅读,并可能在将来导致问题。

在第二个函数中,您希望迭代要删除的项目,而不是原始列表,然后删除所有项目。

使用:

def remove_items_from_list(ordered_list, items_to_remove):
    for item_to_remove in items_to_remove:
        ordered_list.remove(item_to_remove)

并且在迭代时不要更改a列表,这可能会导致错误。

空行数纯粹是一个;它不会影响代码的行为。顺便说一句,请记住,在for语句中,for后面的标识符定义了一个新变量作为循环变量。如果将其命名为函数的参数,则会隐藏参数变量并使其无法访问。你永远不想隐藏你的参数变量,这很混乱。我明白了,所以变量'item'可以命名为任何东西,它保存着每个列表元素的值。非常感谢。