Collection and operations

Collection and operations

#_author: Administrator 
#date: 2019/10/31
# collection (focus)
# create a collection of
# sets are unordered, not duplicate, set variable collection (you can add and delete elements, non-hash, not as dictionary key, can not be used as the other elements of the set)
S = sET ( 'of Mr. starrr')
Print (S) {# 'a', 'R & lt', '.', 'M', 'T', '', 's'} set may remove duplicate content
a = [' ALE ',' eveb ',' ALE ',' MX ']
Print (sET (a)) # {' eveb ',' ALE ',' MX '}
Print (type (SET (a))) # <class' SET '>
# into a list of
B = list (SET (a))
Print (B) # [' MX ',' ALE ',' eveb ']
Print (type (B)) # <class' List'>
#Notice: collection element must be a hash, i.e., the same type
# M1 = [[1,2], 'Star', 123]
# n- SET = (M1)
# Print (n-) #TypeError: unhashable type: 'List'
#
# m2=[{1:1},'star',123]
# n2=set(m1)
# print(n2)#TypeError: unhashable type: 'dict'
# (2) .frozenset is immutable collection
M3 = [ 'Q', l, 4]
N3 = frozenset (M3)
Print (N3) #frozenset ({. 1, 'Q',}. 4)
Print (type (N3) ) # <class 'frozenset'>
# 2. access set (for loop, or use in)
Q = [l, 4, 'Star']
S1 = sET (Q)
Print (in S1. 4) #True
#. 3. update set
# (. 1)
s1.add ( 'U') to add an element #
Print (S1). 1 {#, 'Star',. 4, 'U'}
s1.add ( 'Uu')
Print (S1). 1 {# , 'Star',. 4, 'Uu'}
# (2) Update
D = [. 1, 'A', 'ZXC', 'Star']
X = SET (D)
x.update ( 'eeeo') # single character was added into
print (X) {# 'E',. 1, 'a', 'O', 'Star', 'ZXC'}
x.update ([234, 'WOP']) # added as a whole into
print ( x) # { 'wop', 1,'zxc', 'star', 234, 'o', 'a', 'e'}
x.remove('zxc')
print(x)#{1, 'star', 'wop', 234, 'a', 'e', 'o'}
x.pop () # remove random
Print (X)
x.clear ()
Print (X) #set ()
# del X
# Print (X) #NameError: name 'X' IS Not defined
# collection type. 4 operator.
# (1) is not equivalent to a set of equivalent
Print (sET ( 'ASD') == sET ( 'asdsdsd')) True #
# (2) subset super
print (set ( 'asd') <set ( ' asdhdjhwud ')) # True
# (. 3) United
Print (SET (' ASD ') or SET (' asdhdjhwud ')) # {' A ',' S ',' D '}
Print (SET (' ASD ') and SET ( 'asdhdjhwud')) {# 'H', 'D', 'A', 'U', 'S', 'W', 'J'}
# intersection
a = set ([1,2,3, 4,5])
B = sET ([4,5,6,7,8])
Print (a.intersection (B)). 4 {#,} Print. 5 (A & B)
# and set
print (a.union (b)) # {1, 2, 3, 4, 5, 6, 7,8}同 a | b
#差集
print(a.difference(b))#{1, 2, 3} in a not but in b 同print(a-b)
print (b.difference (a)) # {8, 6, 7} with Print (BA)
# symmetric difference
Print (a.symmetric_difference (B)) {#. 1, 2,. 3,. 6,. 7,. 8}

# parent superset
Print (a.issuperset (B)) False # A> B
# subset
Print (a.issubset (B)) False # A <B
# another implementation,
a = set ([1,2,3 , 4,5])
B = SET ([4,5,6,7,8])
Print (ab &) {#. 1, 2,. 3}
Print (BA). 8 {#,. 6,}. 7
Print (& A B) # {. 4,. 5}
Print (A | B) # {. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8}
Print (A ^ B) # {. 1, 2,. 3,. 6,. 7, 8}




Guess you like

Origin www.cnblogs.com/startl/p/11772946.html