Python基础之集合,,Python基础三:


Python基础三:
一、数据类型排序:
可变与不可变:
1、可变:列表,字典
2、不可变:字符串,元组,数字
访问顺序:
1、直接访问:数字
2、顺序访问:字符串,列表,元组
3、映射:字典
存放元素个数:
1、容器类型:列表,元组,字典
2、原子类型:数字,字符串

二、集合
特点:
1、不同元素组成
2、是无序的
3、集合中的元素必须是不可变类型(数字,字符串,元组)
4、定义集合的方式:test = {‘xyy‘,‘xyyp‘,1,2,3,4}或test = set(‘xyy‘)

三、集合功能:
add() 往集合中添加元素,一次只能添加一个元素

test = {‘xyy‘,‘xyyp‘,1,2,3,4}test.add(5)test.add(‘xyp‘)print(test)

结果:

技术分享

clear() 清空集合内容

test = {‘xyy‘,‘xyyp‘,1,2,3,4}test.clear()print(test)

结果:

技术分享

copy() 复制一份新的集合内容

test = {‘xyy‘,‘xyyp‘,1,2,3,4}n = test.copy()print(n)

结果:

技术分享

pop() 删除随机的一个元素

test = {‘xyy‘,‘xyyp‘,1,2,3,4}test.pop()print(test)

结果:
技术分享

remove() 删除指定的内容,如果指定的内容不存在会报错

test = {‘xyy‘,‘xyyp‘,1,2,3,4}test.remove(‘xyyp‘)print(test)

结果:
技术分享

discard() 删除指定的内容,如果指定的内容不存在不会报错

test = {‘xyy‘,‘xyyp‘,1,2,3,4}test.discard(‘xyy‘)test.discard(‘xyyfg‘)print(test)

结果:

技术分享

update() 往集合里面添加多个元素,比add强大一点

test = {‘xyy‘,‘xyyp‘,‘xyp‘}test.update((‘Jony‘,‘Tom‘)) // 添加的是元组的话结果就是完整的字符串 test.update(‘Jony‘,‘Tom‘) // 添加的是字符串的话结果就是单个字符print(test)

结果:

技术分享

isdisjoint() 判断两个集合有木有相同的元素,没有则为真(True)

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyyx‘,‘xypc‘}n = test1.isdisjoint(test2) // test1和test2没有相同的元素print(n)

结果:

技术分享

四、Python的集合关系运算:
1、交集:intersection() 会输出两个集合的相同内容

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘} // 定义两个集合,两个集合有相同和不同的元素test2 = {‘xyy‘,‘xyp‘,‘fg‘}n = test1.intersection(test2) print(n)

结果:
技术分享

或者:

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n = test1&test2 // intersection可以用&符号代替print(n)

结果:

技术分享

2、并集:union() 会输出两个集合的不同内容,并合成一个集合

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n = test1.union(test2)print(n)

结果:
技术分享

或者:

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n = test1|test2 // 一个竖线(|)就表示union这个功能print(n)

3、差集:difference()第一个集合减去第二个集合得出第一个集合不同于第二个集合的一个元素,反过来意思一样

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n1 = test1.difference(test2) //test1集合减去test2集合n2 = test2.difference(test1) //test2集合减去test1集合print(n1,n2)

结果:

技术分享

或者:

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n1 = test1-test2 // 用减号(-)代替differenceprint(n1)n2 = test2-test1print(n2)

结果:

技术分享

4、交叉补集:symmetric_difference()只取两个集合不同的部分

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘fg‘}n2 = test1.symmetric_difference(test2)print(n2)

结果:
技术分享

或者:

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘,‘Tom‘}n = test1^test2 //symmetric_difference()可以用^代替print(n)

结果:

技术分享

5、子集:issubset()判断谁是谁的子集

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘}n = test2.issubset(test1) //两个集合有相同的部分,但是第二个比第一个元素少,所以第二个是第一个的子集print(n)

结果:

技术分享

6、父集:issuperset()判断谁是谁的父集

test1 = {‘xyy‘,‘xyyp‘,‘xyp‘}test2 = {‘xyy‘,‘xyp‘}n = test1.issuperset(test2) //两个集合有相同的部分,但是第一个比第二个元素多,所以第一个是第二个的父集print(n)

结果:

技术分享

Python基础之集合

评论关闭