Python set of common methods and summary

The concept of the collection

Unordered set is a variable, the element can not be repeated. In fact, the dictionary is a collection of the underlying implementation of all elements of the collection are the dictionary
of "key target" and therefore can not be repeated and unique.

Collection creation and deletion

{} Used to create a set of objects, and use add () method to add an element

>>> a = {3,5,7}
>>> a
{3, 5, 7}
>>> a.add(9)
>>> a
{9, 3, 5, 7}

Use SET (), the list of tuples like object into a collection may be iteration.

If the original data is duplicate data, leaving only a

>>> a = ['a','b','c','b']
>>> b = set(a)
>>> b
{'b', 'a', 'c'}

remove () Removes the specified element; clear () empty the entire collection

>>> a = {10,20,30,40,50}
>>> a.remove(20)
>>> a
{10, 50, 30}
>>> a = {10,20,30,40,50}
>>> a.clear()
>>> a
set()

A collection of related operations

Like the concept of mathematics, Python is also provided for the collection of union, intersection, difference and other operations. We give an example:

>>> a = {1,3,'sxt'}
>>> b = {'he','it','sxt'}
>>> a|b #并集
{1, 3, 'sxt', 'he', 'it'}
>>> a&b #交集
{'sxt'}
>>> a-b #差集
{1, 3}
>>> a.union(b) #并集
{1, 3, 'sxt', 'he', 'it'}
>>> a.intersection(b) #交集
{'sxt'}
>>> a.difference(b) #差集
{1, 3}

Reproduced in: https://blog.csdn.net/weixin_43158056/article/details/92800395

Guess you like

Origin www.cnblogs.com/x1you/p/12592689.html