python - 在 Python 中,如何从一个或多个列表中删除重复项?

标签 python list duplicates

<分区>

例如,如果我有:

a = ["apples", "bananas", "cucumbers", "bananas"]

我怎样才能删除重复的“香蕉”以便:

a = ["apples", "bananas", "cucumbers"]

此外,如果我有:

a = ["apples", "bananas", "cucumbers"]

b = ["pears", "apples", "watermelons"]

我怎样才能从两个列表中删除重复的“苹果”,以便:

a = ["bananas", "cucumbers"]

b = ["pears", "watermelons"]

最佳答案

基于集合的解决方案不保留项目的顺序。以下将保持项目的顺序并删除除每个项目第一次出现以外的所有项目,使用辅助集来跟踪哪些项目已经被看到。

seen = set()
a = [seen.add(item) or item for item in a if item not in seen]

如果你想重用同一个列表对象,你可以这样做:

seen = set()
a[:] = (seen.add(item) or item for item in a if item not in seen)

关于python - 在 Python 中,如何从一个或多个列表中删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259056/

相关文章:

python - Python 中的 Adwords 数组,没有属性 'get'

Python:将 3 个列表连接到 csv 文件中?

python - 在 Django 模板中循环字典的字典只需 1 行代码

html - 悬停子列表时更改列表选项的颜色

postgresql - 更新一对多关系中的重复项。

sql - 关于重复数据删除软件的建议?

python - 在 Python 中对字典列表中的数据进行排序和组合

python - 具有任意索引的python中的数组

python - 关联列表中的两个项目

php - 双重复 key 更新输入错误