Carambola Python Basics Tutorial - Chapter 5: Python data types (five) collection

I CSDN blog column: HTTPS: //blog.csdn.net/yty_7
Github Address: https: //github.com/yot777/Python-Primary-Learning

 

. 5 .7  six data types Five: Sets ( set)

Collection (set) is a set of unordered elements will not be repeated. By definition, we can get the following three sets of characteristics:

Features a: Element not allowed to repeat , if you enter repeating elements in the initialization list, Python will automatically duplicate elements removed, leaving only a

Features 2: element no particular order, a set of the same elements when used repeatedly arranged in the original order are not necessarily

Features 3: Caucasus can not lead to access specific elements, but can traverse all the elements in a for loop

 

Braces may be used or set () function creates a set collection Note: Creating a empty set must be set () instead of {}

If the individual is a [braces {} is an empty dictionary]

# 举例1:
>>> s = {1,2,3,1,3,4,5}
>>> print(s)
{1, 2, 3, 4, 5}    #Python会自动将重复的元素去掉,只保留一个
>>> print(s[0])    #报错,因为集合中的元素不能加索引
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing

() Function is used to add an element to the collection add. Note: because the elements in the set is unordered, and therefore the position of the additive element is not determined

# 举例2:
>>> t=set()      #创建一个空集合
>>> t.add('a')   #向集合中添加元素a
>>> print(t)
{'a'}
>>> t.add('b')   #向集合中添加元素b
>>> print(t)
{'b', 'a'}       #元素b的位置出现在a的前面
>>> t.add('c')
>>> print(t)     #向集合中添加元素c
{'b', 'c', 'a'}  #元素c的位置在a和b中间,可见集合中元素的位置是不确定的
>>> t.add('a')   
>>> print(t)     #集合中已有元素a因此不会再次添加元素a
{'b', 'c', 'a'}

Relationship between the elements may be performed by the test set operator and eliminating duplicate entries

# 举例3:
>>> a = set('abracadabra') 
>>> b = set('alacazam')
>>> a
{'r', 'c', 'a', 'd', 'b'}   #集合a的元素被Python自动去重
>>> b
{'c', 'a', 'l', 'm', 'z'}   #集合b的元素被Python自动去重

# 举例4:
>>> a - b          #求a和b的差集
{'d', 'b', 'r'}
>>> a | b          #求a和b的并集
{'r', 'c', 'a', 'd', 'b', 'l', 'm', 'z'}
>>> a & b          #求a和b的交集
{'c', 'a'}
>>> a ^ b          #求a和b中不同时存在的元素
{'r', 'd', 'b', 'l', 'm', 'z'}

Reference Tutorial:

Liao Xuefeng of Python tutorials

https://www.liaoxuefeng.com/wiki/1016959663602400

Liao Xuefeng's Java Tutorial

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 Tutorial | Tutorial rookie
https://www.runoob.com/python3/
 

If you feel Benpian chapter has helped you, welcome attention, comments, thumbs up! Github welcome you Follow, Star!
 

Published 25 original articles · won praise 3 · Views 2168

Guess you like

Origin blog.csdn.net/yty_7/article/details/104136099