python - 遍历列表,比较值并删除重复项 - Python

我很好奇。如何正确地遍历列表、比较两个值并删除重复项(如果存在)。

这里我创建了一个嵌套的 for 循环:

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

def remove_items_from_list(ordered_list, temp):
    # Removes all values, found in items_to_remove list, from my_list
        for j in range(0, len(temp)):
                for i in range(0, len(ordered_list)):
                        if ordered_list[i] == temp[j]:
                                ordered_list.remove(ordered_list[i])

但是当我执行我的代码时出现错误:

  File "./lab3f.py", line 15, in remove_items_from_list
    if ordered_list[i] == items_to_remove[j]:

谁能解释一下为什么?

这个问题,我想比较两个列表,这些列表有两个不同的长度。如果列表 a 中的某个项目与列表 b 中的某个值匹配,那么我们希望将其从列表 a 中删除。

最佳答案

您实际上可以在遍历列表时从列表中删除项目,但一定要阅读 @ReblochonMasque 的链接。

这是删除重复项的一种方法:

def remove_items_from_list(ordered_list, temp):
    n = len(ordered_list)
    for i in range(n - 1, -1, -1):
        if ordered_list[i] in temp:
            del ordered_list[i]      

然后

>>> remove_items_from_list(my_list, temp)
>>> print(my_list)
[2, 3, 4]

但是,解决问题的最简单方法之一是使用集合:

list(set(my_list) - set(temp))

使用这种方法时,结果列表中项目的顺序可能是任意的。此外,这将创建一个 列表而不是修改现有的列表对象。如果顺序很重要 - 使用列表理解:

[v for v in my_list if v not in temp]

https://stackoverflow.com/questions/50635960/

相关文章:

r - 重新启动的组计数器(使用 R data.table)

python-3.x - 如何在不更改 css 的情况下共享 pytest-html 的 html

xamarin - 类型 'StackLayout' 的值不能添加到类型 'IList' 的集合或字

reactjs - 我如何模拟 reactjs 中的 promise ?

javascript - 如何从url获取json数据并保存到const变量【TypeScript】

python - 如何使用具有 NaN 值的 Pandas 计算中位数?

qt - 没有安装 qmlscene : why is a warning sign next to

java - 如何为不同类型的异常设置不同的状态码

powershell - 在 PowerShell 中比较字符串中的日期

php - 如何显示在 php 中使用 file_get_contents 检索到的 pdf?