Python 列表减法

标签 python

<分区>

这是练习示例:

Write a function (list1, list2) that takes in two lists as arguments and return a list that is the result of removing elements from list1 that can be found in list2.

为什么这个函数返回 [1, 3, 4] 而不是我想的 [4]?我认为它与 list1.remove() 有关。我想这很明显,但我看不到。

它适用于这些示例:

subtractList (['a', 'b', 'c', 'd'], ['x', 'y', 'z']) =
    ['a', 'b', 'c', 'd']

subtractList([1,2,3,4,5], [2, 4]) =
    [1, 3, 5]

但失败了:

subtractList(range(5), range(4))

我还注意到它只从列表中删除偶数。

代码如下:

def subtractList(list1,list2):
    list1 = list(list1)
    list2 = list(list2)

    for i in list1:
        if i in list2:
            list1.remove(i)

    return list1

我已经解决了这个问题:

def subtractList(list1,list2):

    new_list = []

    list1 = list(list1)
    list2 = list(list2)

    for i in list1:
        if i not in list2:
            new_list.append(i)

    return new_list

最佳答案

在遍历列表时更改列表会导致问题。您的第二个解决方案不错,或者您可以查看“列表理解”。在这种情况下:

new_list = [num for num in list1 if num not in list2]

关于Python 列表减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328663/

相关文章:

python - 如何将 json 转换为 Python 列表?

python - 在python中将标题写入excel文件

python - 在 Python 的 OpenCV 中找不到 cv2.cv 模块

python - 有人可以解释这条扭曲的事吗?

python - 在 gevent 中检测客户端断开连接

linux - 将 bash 脚本转换为 python

python - 在虚拟环境中使用 pip 构建 uwsgi 时出错

python - 在Windows中使用python获取重启历史记录

解析文件的Python函数适用于单个文件,但不适用于批处理

python - 机器学习-如何使用过去的 20 行作为每个 Y 值的 X 的输入