首页 > 解决方案 > Can a list with repeating values be converted into a multiset in python?

问题描述

I am having two lists with repeating values and I wanted to take the intersection of the repeating values along with the values that have occurred only once in any one of the lists. I am just a beginner and would love to hear simple suggestions!

标签: python-3.xlistmultiset

解决方案


方法一

l1=[1,2,3,4]
l2=[1,2,5]
intersection=[value for value in l1 if value in l2]
for x in l1+l2:
    if x not in intersection: 
        intersection.append(x)
print(intersection)

方法二

print(list(set(l1+l2)))

推荐阅读