Home  >  Article  >  Backend Development  >  python basics-set collection

python basics-set collection

巴扎黑
巴扎黑Original
2016-12-03 09:58:46995browse

set set is an unordered and non-repeating set of elements

1.set creation

2 ways:

se = {11,22,33}
se = set([11,22,33]) #Call the __init__ method of set to create

2.Common methods of set

1.add

se = {11,22,33}se.add(44)
print(se) => {33,11,44,22} #Because it is unordered, the execution result will be different, but 44 is indeed added to the original set set

2.remove

se = {11,22,33 }
se.remove(11)
print (se) => {22,33}
se.remove(44) #Error report, prompting that the specified element cannot be found

3.discard

se = {11 ,22,33}se.discard(11)
print (se) => {22,33}se.discard(44)
print (se) => {11,22,33} #Cannot find the specified element, no deletion, no error

4.pop

se = {11,22,33}
se.pop()print (se) => {11,22} # Randomly pop an element from the stack , the execution results may be different ret = se.pop()print (ret) => {33} #Print the result of popping out the stack

5.difference

se1 = {11, 22, 33, 44}
se2 = {22, 33, 44, 55}
print(se1.difference(se2)) = > 11 # Print elements that exist in se1 but do not exist in se2 print(se2.difference(se1)) = > ; 55 #Print elements that exist in se2 but do not exist in se1

6.difference_update

se1 = {11,22,33,44}
se2 = {22,33,44,55}
se1.difference_update (se2)print (se1) => 11 #Overwrite the elements that exist in se1 and do not exist in se2 to se1, and update the set collection

7.intersection

se1 = {11,22,33,44 }
se2 = {22,33,44,55}
print (se1.intersection(se2)) => {22,33,44} #Se1, se2 intersection

8.intersection_update

se1 = { 11,22,33,44}
se2 = {22,33,44,55}
se1.intersection_update(se2)
print (se1) => {33,44,22} #Overwrite the intersection of se1 and se2 Write to the set of se1

9.union

se1 = {11,22,33,44}
se2 = {22,33,44,55}
print (se1.union(se2)) => {11,22,33,44,55} #se1, the union of se2


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:python basics-operatorsNext article:python basics-operators