【问题标题】:Python - iterating over listsPython - 遍历列表
【发布时间】: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


【解决方案1】:

在您的 remove_items_from_list 函数中,您正在遍历错误的列表。您应该像这样遍历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) 

现在这将遍历删除列表中的每个项目并将其从您的ordered_list 中删除。

【讨论】:

  • 我明白了,所以变量“item”(可以命名任何东西)保存每个列表元素的值。谢谢!
【解决方案2】:

remove_items_from_list 函数中存在错误。为了它实现你想要的它应该去:

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)

附带说明,您的代码在函数定义之前的空行数不正确。函数前应该有两个空行,函数内部不超过一个空行。它目前似乎没有影响代码,但使其更难阅读,并可能在未来引起问题。

【讨论】:

  • 空行数纯属style issue;它不会影响代码的行为。
【解决方案3】:

在第二个函数中,您要遍历 items_to_remove(而不是您的原始列表),然后删除每个项目。

【讨论】:

    【解决方案4】:

    用途:

    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列表,这可能会导致错误。

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 1970-01-01
      • 2015-10-07
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多