Introduction to python3 collections

高洛峰
Release: 2017-03-26 18:31:57
Original
1261 people have browsed it

This article mainly provides an in-depth analysis of the introduction to python3 collections, which has certain reference value. Interested friends can refer to it

# Auther: Aaron Fan

'''
集合是一个无序的,不重复的数据组合,它的主要作用如下:
去重,把一个列表变成集合,就自动去重了
关系测试,测试两组数据之前的交集、差集、并集等关系
'''

list_1 = [1,3,4,7,3,6,7,9]
#去重
list_1 = set(list_1)

list_2 = set([2,6,0,66,22,8,4])
list_3 = set([1,3,7])
print(list_1)
print(list_2)
print(list_3)
print("---------------------------")

#关系测试
#交集(两个列表里面都有的值,这里是4、6):
print(list_1.intersection(list_2))

#并集(把两个列别合并起来,然后去重):
print(list_1.union(list_2))

#差集(把list_1里面有的而list_2里面没有的取出来):
print(list_1.difference(list_2))
#对称差集(两个列表里面,互相没有的取出来,也就是只去掉那些互相都有的值)
print(list_1.symmetric_difference(list_2))

#子集(判断list_1是否包含了list_3里面的所有值)
print(list_3.issubset(list_1))
#父集(判断list_1是否为list_3的父集)
print(list_1.issuperset(list_3))

#无交集(判断list_3和list_4是否完全没有任何交集)
list_4 = set([5,6,8])
print(list_3.isdisjoint(list_4))

#-----------------------关系测试的另一种写法:
'''
s = set([3,5,9,10])      #创建一个数值集合

t = set("Hello")         #创建一个唯一字符的集合


a = t | s          # t 和 s的并集

b = t & s          # t 和 s的交集

c = t – s          # 求差集(项在t中,但不在s中)

d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)

基本操作:

t.add('x')            # 添加一项

s.update([10,37,42])  # 在s中添加多项



使用remove()可以删除一项:

t.remove('H')   #有就删除,没有就报错
t.pop() #随机弹出一个
t.discard('H')  #有就删除,没有也不会报错

len(s)
set 的长度

x in s
测试 x 是否是 s 的成员

x not in s
测试 x 是否不是 s 的成员

s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中

s.issuperset(t)
s >= t
测试是否 t 中的每一个元素都在 s 中

s.union(t)
s | t
返回一个新的 set 包含 s 和 t 中的每一个元素

s.intersection(t)
s & t
返回一个新的 set 包含 s 和 t 中的公共元素

s.difference(t)
s - t
返回一个新的 set 包含 s 中有但是 t 中没有的元素

s.symmetric_difference(t)
s ^ t
返回一个新的 set 包含 s 和 t 中不重复的元素

s.copy()
返回 set “s”的一个浅复制
&#39;&#39;&#39;
Copy after login

The above is the detailed content of Introduction to python3 collections. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!