程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Finding intersection, union and difference between two lists in Python

編輯:Python

Hello everyone , I meet you again , I'm your friend, Quan Jun .

project github Address :bitcarmanlee easy-algorithm-interview-and-practice Students often send private letters or leave messages to ask relevant questions ,V Number bitcarmanlee.github On star Classmate , Within my ability and time , Try to help you answer relevant questions , Progress together .

stay python in , Arrays can use list To express . If you have two arrays , Intersection required separately , Union and difference sets , How to make it more convenient ? Of course, the easiest thing to think of is looping through two arrays , Write two for Loop to achieve . Most students should know this way of writing , And there is not much technical content , The blogger will not explain . It is more convenient to use here bility Some of the ways .

Old rules ,talk is cheap,show me the code

#!/usr/bin/env python
#coding:utf-8
'''
Created on 2016 year 6 month 9 Japan
@author: lei.wang
'''
def diff(listA,listB):
# Two ways to find the intersection
retA = [i for i in listA if i in listB]
retB = list(set(listA).intersection(set(listB)))
print "retA is: ",retA
print "retB is: ",retB
# Union
retC = list(set(listA).union(set(listB)))
print "retC1 is: ",retC
# Difference set , stay B But not in A in
retD = list(set(listB).difference(set(listA)))
print "retD is: ",retD
retE = [i for i in listB if i not in listA]
print "retE is: ",retE
def main():
listA = [1,2,3,4,5]
listB = [3,4,5,6,7]
diff(listA,listB)
if __name__ == '__main__':
main()

Give Way code run get up

retA is: [3, 4, 5]
retB is: [3, 4, 5]
retC1 is: [1, 2, 3, 4, 5, 6, 7]
retD is: [6, 7]
retE is: [6, 7]

Combined with the code , Basically, there are two ways of thinking : 1. Use list parsing . List parsers are generally faster than loops , And more pythonic Look more awesome . 2. take list Turn into set in the future , Use set Various ways to deal with .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/151880.html Link to the original text :https://javaforall.cn


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved