Collection : Used to contain a set of unordered objects ;
It can be understood that putting a list in {} makes up a collection
Create a collection : Use the Set function or use {} and provide the item to be stored, such as:
s = set ([3,5,9,10]) #创建一个数据集合e = {1,2,3,4,6,7,8} #也可以这样创建一个数据集合t = set (' Hello ') #创建一个唯一字符的集合
Differences from lists and tuples:
1, the collection is unordered
2, cannot be indexed by number
3, the collection element cannot be repeated each element is unique
Check the values in the T collection:
Print (t)
Output a set of unordered:
{' H ', ' o ', ' e ', ' l '}
The collection supports a range of standard operations, including the set, intersection, difference set, and symmetric difference sets such as:
A = T|s #求并集b = T&s #求交集c = S-t #求差集d = t ^s # symmetric difference set
Explain:
| : Two merged objects of a collection
&: Two objects that exist at the same time as a collection
- : item exists in t but does not exist in S
^ : Two objects in a collection that do not exist concurrently
Output Result:
{3, 4, 5, 6, 7, ' e ', ' l ', ' H ', ' O '}
Set ()
{' H ', ' l ', ' e ', ' O '}
{3, 4, 5, 6, 7, ' e ', ' o ', ' H ', ' l '}
Two ways to add data to a collection:
1,add () Method: Add an item
data = {1,2,3,4,5};d ata.add (6);p rint (data);
Output Result:
{1, 2, 3, 4, 5, 6}
2,update () Method: Add multiple items
Data.update (' ABC ');
#也可以使用 data.update (' A ', ' B ', ' C ');
Output Result:
{1, 2, 3, 4, 5, 6, ' A ', ' B ', ' C '}
method of deleting an item in the collection:
Remove () Method:
Data.remove (' A ');
Output Result:
{1, 2, 3, 4, 5, 6, ' B ', ' C '}
question: Why should there be a collection ?
Practice:
In the list, if you want to remove duplicates:
data = [' A ', ' B ', ' a ', ' C ', 1,2,3,2,4,1,3];all = [];for num in data: The #循环data数据 if num not in all: #如果不存在于列表all中 All.append (nu m); #则追加print (All);
Output Result:
{1, 2, 3, 4, ' A ', ' B ', ' C '}
to use the collection simplification list to remove the weight :
data = List (set (data));p rint (data);
explain : Because the objects in the collection are unique, the data declaration becomes a collection after the duplicates are removed and then converted to the list
Note : Because the set is unordered, the resulting sequence of results changes and is used with caution when the output order is specified
Output Result:
{1, 2, ' B ', ' C ', 3, ' A ', 4}
Summarize:
1, How to create a collection: Set () {}
2, the difference between a collection and a list, a tuple: unordered cannot index and slice objects are unique
3, how to find the intersection difference set symmetric difference set (|,&,-,^)
4, two ways to add and one way to delete: Add (), update (), remove ()
5, Practice: How to Use Collections: List (set (data));
This article is from the "Hong Dachun Technical column" blog, please be sure to keep this source http://hongdachun.blog.51cto.com/9586598/1761121
Collections in Python