python note 07 集合

1、删除特例

lis = [11,22,33,44,55]
for i in range(len(lis)):
    print(i)
    del lis[i]
    print(lis)
#每删除链表中一个值链表就会前移一位

 

2、删除字典的值

dic = {'k1':'v1','k2':'v2','a3':'v3'}
dic1 = {}
l = []
for i in dic:
    if 'k' in i:
        l.append(i)
for i in l:
    del dic[i]
print(dic)
#输出{'a3': 'v3'}

 

3、bool值的转换

0 ' '  [] () {} set() 为False

 

4、如果元祖里面只有一个元素且不加逗号那此元素是什么类型,就是什么类型。

tu1 = (1)
tu2 = (1,)
print(tu1,type(tu1))
#输出1 <class 'int'>
print(tu2,type(tu2))
#输出(1,) <class 'tuple'>

 

tu1 = ([1])
tu2 = ([1],)
print(tu1,type(tu1))
#输出[1] <class 'list'>
print(tu2,type(tu2))
#输出([1],) <class 'tuple'>

 

5、集合:可变的数据类型,他里面的元素必须是不可变的数据类型,无序,不重复。

#增

set1 = {'alex','wusir','ritian','egon','barry',}
set1.add('pzw')
print(set1)
#输出{'pzw', 'barry', 'alex', 'ritian', 'egon', 'wusir'}

不同于第一种

set1 = {'alex','wusir','ritian','egon','barry',}
set1.update('pzw')
print(set1)
#输出{'alex', 'z', 'w', 'ritian', 'barry', 'p', 'wusir', 'egon'}

 

#删

set1 = {'alex','wusir','ritian','egon','barry',}
set1.pop()  # 随机删除
print(set1)
#输出{'ritian', 'wusir', 'alex', 'barry'}

有返回值删除

set1 = {'alex','wusir','ritian','egon','barry',}
print(set1.pop())  # 有返回值
print(set1)
#输出barry
#    {'alex', 'wusir', 'egon', 'ritian'}

按元素删除

set1 = {'alex','wusir','ritian','egon','barry',}
set1.remove('alex')  # 按元素删除
print(set1)
#输出{'barry', 'egon', 'wusir', 'ritian'}

清空集合

set1 = {'alex','wusir','ritian','egon','barry',}
set1.clear()
print(set1)
#输出set()

 

#查

set1 = {'alex','wusir','ritian','egon','barry',}
for i in set1:
    print(i)

 

6、集合的交并集

交集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1 & set2
print(set3)
#输出{4, 5}
print(set1.intersection(set2))
#输出{4, 5}

并集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 | set2) 
#输出{1, 2, 3, 4, 5, 6, 7, 8}
print(set2.union(set1))
#输出{1, 2, 3, 4, 5, 6, 7, 8}

反交集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 ^ set2)
#输出{1, 2, 3, 6, 7, 8}
print(set1.symmetric_difference(set2))
#输出{1, 2, 3, 6, 7, 8}

差集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 - set2)
#输出{1, 2, 3}
print(set1.difference(set2))
#输出{1, 2, 3}

子集与超集

set1 = {1,2,3,}
set2 = {1,2,3,4,5,6}
print(set1 < set2)
print(set1.issubset(set2))  # 这两个相同,都是说明set1是set2子集。
print(set2 > set1)
print(set2.issuperset(set1))  # 这两个相同,都是说明set2是set1超集。

 

7、去重

li = [1,2,33,33,2,1,4,5,6,6]
set1 = set(li)
print(set1)
#输出{1, 2, 33, 4, 5, 6}
li = list(set1)
print(li)
#输出[1, 2, 33, 4, 5, 6]

 

特例

s = frozenset('barry')
print(s,type(s))
#输出frozenset({'r', 'b', 'y', 'a'}) <class 'frozenset'>

 

8、赋值运算

l1 = [1,2,3]
l2 = l1
l1.append('a')
print(l1,l2)
#输出[1, 2, 3, 'a'] [1, 2, 3, 'a']

#copy

l1 = [1,2,3]
l2 = l1.copy()
print(l1,l2)
#输出[1, 2, 3] [1, 2, 3]

 

l1 = [1,[1],2,3,4]
l2 = l1[:]
l1[1].append('a')
print(l1,l2)
#输出[1, [1, 'a'], 2, 3, 4] [1, [1, 'a'], 2, 3, 4]

 

li = ['alex','taibai','wusir','egon']
for i in li:
    print(li.index(i),i)
#输出 0 alex
#    1 taibai
#    2 wusir
#    3 egon

 

posted @ 2019-03-16 17:08  P-Z-W  阅读(170)  评论(0编辑  收藏  举报