python-13- deletions search set

Foreword

Set: a variable data type, but the type of data elements must be immutable, disorder not repeat, can hash. So a collection of python that can not be modified, only the additions and deletions to check.
Hashable, immutable data types: tuples, bool, int, str

First, by

1, add, because it is disordered, each print is random saw new location

# . 1, the Add, disordered, random 
setl = { ' Tian ' , ' tiger ' }
set1.add('long')
print(set1)

 2, update, in accordance with new elements

# 2, Update 
setl = { ' Tian ' , ' tiger ' }
set1.update('ab')
print(set1)

 Second, delete

1, pop () Delete

# . 1, POP () Delete 
setl = { ' Tian ' , ' tiger ' , ' Xiao ' }
 Print (set1.pop ())          # randomly delete, return values 
Print (setl)

 2, remove deleted by elements

# 2, the element deletion according Remove 
setl = { ' Tian ' , ' tiger ' , ' Xiao ' }
set1.remove('tian')
print(set1)

 3, clear empty

# 3、清空
set1 = {'tian', '小龙', 'xiao'}
set1.clear()
print(set1)

 4、del 删除,没有返回值

# 4、del 删除,没有返回值
set1 = {'tian', '小龙', 'xiao'}
del set1

 三、查

1、交集、并集、反交集、差集,可bool、int、str

set1 = {4, 5, 6, 7, 8}
set2 = {12, 1, 5, 7, 9}
print(set1 & set2)          # 交集

print(set1 | set2)          # 并集,去重

print(set1 ^ set2)          # 反交集

print(set1 - set2)          # 差集

 2、子集、超集,返回:bool

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1 < set2)          # 子集,set1 是 set2的子集
print(set2 > set1)          # 超集,set2 是 set1的超集

 3、有个需求将列表的数据去重,不改变原来的类型。(PS:1.二次转换;2.frozenset)

① 列表转换为集合,集合再转回列表

li = [1,2,33,33,2,1,4,5,6,'a','a']
# # 将列表转换为集合,集合再转回列表即可
s = set(li)
print(list(s))

② frozenset

li = []
s = frozenset([1,2,33,33,2,1,4,5,6,'a','a'])
print(s, type(s))
for i in s:
    li.append(i)
print(li)

 

你更喜欢哪种呢?欢迎来QQ交流群:482713805

Guess you like

Origin www.cnblogs.com/gsxl/p/11966230.html