列出两个列表中差别的 Python 程序。
本题中给出了两个列表。我们的任务是显示两个列表之间的差异。Python 提供了 set() 方法。我们在这里使用这种方法。集合是一个无序集合,没有重复的元素。集合对象还支持数学运算,如并集、交集、差集和对称差集。
示例
Input::A = [10, 15, 20, 25, 30, 35, 40] B = [25, 40, 35] Output: [10, 20, 30, 15]
说明
difference list = A - B
算法
Step 1: Input of two arrays. Step 2: convert the lists into sets explicitly. Step 3: simply reduce one from the other using the subtract operator.
示例代码
# Python code to get difference of two lists
# Using set()
def Diff(A, B):
print("Difference of two lists ::>")
return (list(set(A) - set(B)))
# Driver Code
A=list()
n1=int(input("Enter the size of the first List ::"))
print("Enter the Element of first List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
B=list()
n2=int(input("Enter the size of the second List ::"))
print("Enter the Element of second List ::")
for i in range(int(n2)):
k=int(input(""))
B.append(k)
print(Diff(A, B))
输出
Enter the size of the first List ::5 Enter the Element of first List :: 11 22 33 44 55 Enter the size of the second List ::4 Enter the Element of second List :: 11 55 44 99 Difference of two lists ::> [33, 22]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP