Operation of the set of python

set: collection

Features: automatic de-duplication feature

s = set () # empty set

s2 = set{'1234445566778'}

print(s2)  # ('12345678')

s3 = { '1', '1', '2', '2', '3'}

 

Intersection

print ( s3 & s2)

print ( s3.intersection(s2))

And Set: a set of two bonded together deduplication

print ( s2 | s3 )

print ( s2.union ( s3 ) )

 

s4 = {1,2,3}

s5 = {1,4,6}

Difference-set: s4 has set, s5 no set of elements

print (s4 - s5)

print (s4.difference (s5) )

 

Symmetric difference: remove both the set of common elements

print (s4 ^ s5)

print ( s4.symmetric_diference(s5))

 

Add elements in the collection:

s4.add ('ss')

s4.pop () # delete a random element

s4.remove ( 'ss') # delete the specified element

s4.update ({1,2,3}) # to a set further added to the list

 

lis = [1,1,2,3,4,5,6,8]

for i in lis:

  if i%2 != 0:

    lis.remove(i)

print (lis) # lis = [1,3,5]

 

---------------------------------------------------------------

 

lis1 = [1,1,2,3,4,5,6,8] # 1 opened up a memory

lis2 = [1,1,2,3,4,5,6,8] # 2 opens a memory

for i in lis2:

  if i%2 != 0:

    lis1.remove(i)

print(lis1) # lis1 =[1,2,4,6,8]

 

-----------------------------------------------------

 

lis1 = [1,1,2,3,4,5,6,8]

lis2 = lis1 # Copy shallow, point to the same memory address, the value taken at the same

for i in lis2:

  if i%2 != 0:

    lis1.remove(i)

print(lis1) # lis1 =[2,4,6,8]

 

-----------------------------------------------------

 

lis1 = [1,1,2,3,4,5,6,8]

lis2 = copy.deepcopy (lis1) # deep copy, the other opened a memory

for i in lis2:

  if i%2 != 0:

    lis1.remove(i)

print(lis1) # lis1 =[2,4,6,8]

Guess you like

Origin www.cnblogs.com/up-day/p/11951764.html