总算彻底搞懂Python集合了
集合(set)是一种无序的不重复元素序列,可以使用大括号{}或者set()函数创建集合。
它是Python中一个非常重要,且频繁用到的概念。无论是在日常开发过程中,还是在面试过程中都会经常遇到,今天就来11不为人知的集合用法。
程序员宝藏库:https:github。comJackpopcCSBooksStoredifference(set)
set1。difference(set2):这个方法帮助你获得两个集合之间的差异,换句话说,它让你获得存在于set1中而不存在于给定集合(set2)中的元素。example1recepierequirements{orange,chocolate,salt,pepper}whatIhave{apple,banana,salt}Ihavetobuyorangechocolatepepperprint(Ihavetobuy,recepierequirements。difference(whatIhave))example2allsubscribers{aya,john,smith,sparf,kyle}admins{aya,sparf}usersallsubscribers。difference(admins){kyle,smith,john}print(users)union(set)
set1。union(set2):(set1Uset2)这个set方法返回一个包含set1的元素和set2的元素的集合,此外,返回的集合只包含唯一的元素。admins{aya,sparf}users{aya,kyle,smith,john}allsubscribersadmins。union(users){smith,aya,sparf,kyle,john}print(allsubscribers)intersection(set)
set1。intersection(set2):取两个集合的交集,只返回同时存在于set1和set2中的元素。shop{orange,pepper,banana,sugar}whatIhave{orange,sugar}Ishouldnotbuy{orange,sugar}becauseIhavethem!print(fIshouldnotbuy{shop。intersection(whatIhave)}becauseIhavethem!)issubset()
set1。issubset(set2):检查set1的所有元素是否存在于set2中。nearestlibrarybooks{thepowerofnow,whywesleep,richdadpoordad}necessarybooks{atomichabits,the48lawsofpower,whywesleep}ifnecessarybooks。issubset(nearestlibrarybooks):print(yes,youcanbuythesebooksfromyournearestlibrary)else:print(unfortunately,youhavetogotoanotherlibrary)unfortunately,youhavetogotoanotherlibraryissuperset()
set1。issuperset(set2):检查set2的所有元素是否存在于set1中。nearestlibrarybooks{thepowerofnow,whywesleep,richdadpoordad}necessarybooks{atomichabits,the48lawsofpower,whywesleep}ifnearestlibrarybooks。issuperset(necessarybooks):print(yes,youcanbuythesebooksfromyournearestlibrary)else:print(unfortunately,youhavetogotoanotherlibrary)unfortunately,youhavetogotoanotherlibraryisdisjoint(set)
isdisjoint(set):检查这两个集合是否包含共同的元素。set1{12,38,36}set2{4,40,12}meanscanset1elementset2element0?cansubstructionbezeroset1。isdisjoint(set2)print(cansubstructionbezero)Falsediscard(value),remove(value),pop()
pop():从一个集合中删除一个随机元素。
discard(value):删除一个集合中的指定元素,如果该元素不存在,不会引发错误。
remove(value):删除一个集合中的指定元素,如果该元素不存在,则会引发错误。users{AyaBouchiha,JohnDoe,KyleSmith,NaboSnay}deletedaccountAyaBouchihausers。discard(deletedaccount)users。discard(Hi!)print(users){KyleSmith,JohnDoe,NaboSnay}users。remove(KyleSmith)print(users){NaboSnay,JohnDoe}users。pop()print(users){JohnDoe}users。remove(Hello!)KeyErrorclear()
clear():删除集合中所有元素。countries{Morocco,UK,Spain,USA,UK}print(len(countries))4countries。clear()print(countries)set()print(len(countries))0copy
copy():这个方法让你得到一个指定元素集的副本countries{Morocco,UK,Spain,USA,UK}print(countries){UK,Morocco,Spain,USA}print(countries。copy()){UK,Morocco,Spain,USA}