Python|两个列表之间的区别
可以通过多种方式生成两个列表之间的差异。在本文中,我们将看到可以做到这一点的两种最重要的方法。一种是使用 set() 方法,另一种是不使用它。
例子:
Input :
list1 = [10, 15, 20, 25, 30, 35, 40]
list2 = [25, 40, 35]
Output :
[10, 20, 30, 15]
Explanation:
resultant list = list1 - list2
Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.
In that case, you can maintain a count of each element in both lists.
通过使用 set():
在这种方法中,我们将列表显式转换为集合,然后使用减法运算符简单地从另一个中减少一个。有关集合的更多参考,请访问Python中的集合。
例子:
Python3
# Python code t get difference of two lists
# Using set()
def Diff(li1, li2):
return list(set(li1) - set(li2)) + list(set(li2) - set(li1))
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
print(Diff(li1, li2))
Python3
# Python code t get difference of two lists
# Not using set()
def Diff(li1, li2):
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
li3 = Diff(li1, li2)
print(li3)
输出 :
[10, 20, 30, 15]
不使用 set():
在这种方法中,我们使用基本的组合技术从两个列表中复制元素,并定期检查一个是否存在于另一个中。
例子:
Python3
# Python code t get difference of two lists
# Not using set()
def Diff(li1, li2):
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
li3 = Diff(li1, li2)
print(li3)
输出 :
[10, 20, 30, 15]