【发布时间】:2018-03-08 07:10:52
【问题描述】:
我希望我的代码的第二个函数修改由我的第一个函数创建的新列表。
如果我理解正确,将列表作为参数给出将给出原始列表(在本例中为 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]
谢谢你,很抱歉这个基本问题
【问题讨论】:
-
顺便提一下,请记住,在
for语句中,单词for后面的标识符定义了一个新变量以充当循环变量。当您将其命名为与函数的参数相同时,它会隐藏参数变量并使其不可访问。你永远不想隐藏你的参数变量,这很混乱。
标签: python python-3.x loops for-loop iterated-function