例如,如果我有:
a = ["apples", "bananas", "cucumbers", "bananas"]
我怎样才能删除重复的“香蕉”,以便:
a = ["apples", "bananas", "cucumbers"]
另外,如果我有:
a = ["apples", "bananas", "cucumbers"]
b = ["pears", "apples", "watermelons"]
如何从两个列表中删除重复的“苹果”,以便:
a = ["bananas", "cucumbers"]
b = ["pears", "watermelons"]
答案 0 :(得分:5)
基于集合的解决方案不保留项目的顺序。以下内容将按顺序保留项目并删除除第一次出现之外的所有项目,使用辅助设置来跟踪已经看到的项目。
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)
答案 1 :(得分:3)
使用内置函数set
a = ["apples", "bananas", "cucumbers", "bananas"]
a = list(set(a))
print(a)
在第二种情况下,请使用list comprehension
a = ["apples", "bananas", "cucumbers"]
b = ["pears", "apples", "watermelons"]
r = [i for i in a if i not in b] + [i for i in b if i not in a]
print(r)
答案 2 :(得分:2)
这样做的关键是使用Python的 set 。
所以,在你的第一个例子中,你可以写
a = list(set(a))
集合中还有其他一些有用的方法。
所以,在你的第二个例子中,你可以写
set1 = set(a).intersection(set(b)) #Get elements that are in both lists
set2 = set(a).difference(set1) #Get a set elements that are in a but not in b
a = list(set2) #Convert back to a list
答案 3 :(得分:1)
您可以使用<script type="text/javascript">
var disqus_config = function () {
this.language = "ar";
};
</script>
:
set()
答案 4 :(得分:0)
您可以使用set对象记录重复元素。像这样:
def handle_dumplicate(*lsts):
s = set()
result = []
for lst in lsts:
no_dump_lst = []
for ele in lst:
if ele in s:
continue
s.add(ele)
no_dump_lst.append(ele)
result.append(no_dump_lst)
return result
a = ["apples", "bananas", "cucumbers"]
b = ["pears", "apples", "watermelons"]
a, b = handle_dumplicate(a, b)
print a
print b