setLOGIN

set

Python's set is similar to other languages. It is an unordered set of non-repeating elements. Its basic functions include relationship testing and elimination of duplicate elements. Set is similar to dict, but set does not store value.

1. Creation of set

To create a set, you need to provide a list as the input set

set1=set([123,456,789])
print(set1)

Output result:

{456, 123, 789}

The passed-in parameter [123,456,789] is a list, and the displayed {456, 123, 789} just tells you that there are 3 elements 456, 123, 789 inside this set. The order of display is the same as that in the list in your parameter. The order of the elements is inconsistent, which also shows that the set is unordered.

One more thing, we observe that the output result is in curly brackets. After previous study, we can know that tuple (tuple) uses parentheses, list (list) uses square brackets, dict ( Dictionary) uses curly brackets, and dict is also unordered, except that dict saves key-value pairs, while set can be understood as only saving key values.

Recall that when creating a dict (dictionary), there are duplicate keys, which will be overwritten by subsequent key-value values, and duplicate elements are automatically filtered in the set.

set1=set([123,456,789,123,123])
print(set1)

Output results:

{456, 123, 789}

2. Add elements to set

Elements can be added to the set through the add(key) method, which can be repeated Added, but there will be no effect

set1=set([123,456,789])
print(set1)
set1.add(100)
print(set1)
set1.add(100)
print(set1)

Output result:

{456, 123, 789}
{456, 123, 100, 789}
{456, 123, 100, 789}

3. Set delete element

The set can be deleted through the remove(key) method Elements in

set1=set([123,456,789])
print(set1)
set1.remove(456)
print(set1)

Output results:

{456, 123, 789}
{123, 789}

4. Application of set

Because set is an unordered set of non-repeating elements, therefore , two sets can perform union, intersection, difference and other operations in the mathematical sense.

edac59887302095e82b950a78cdc3c1.png

Example:

set1=set('hello')
set2=set(['p','y','y','h','o','n'])
print(set1)
print(set2)
# 交集 (求两个 set 集合中相同的元素)
set3=set1 & set2
print('\n交集 set3:')
print(set3)
# 并集 (合并两个 set 集合的元素并去除重复的值)
set4=set1 | set2
print('\n并集 set4:')
print(set4)
# 差集
set5=set1 - set2
set6=set2 - set1
print('\n差集 set5:')
print(set5)
print('\n差集 set6:')
print( set6)
# 去除海量列表里重复元素,用 hash 来解决也行,只不过感觉在性能上不是很高,用 set 解决还是很不错的
list1 = [111,222,333,444,111,222,333,444,555,666]  
set7=set(list1)
print('\n去除列表里重复元素 set7:')
print(set7)

Run result:

{'h', 'l', 'e', 'o'}
{'h', 'n', 'o', 'y', 'p'}
交集 set3:
{'h', 'o'}
并集 set4:
{'h', 'p', 'n', 'e', 'o', 'y', 'l'}
差集 set5:
{'l', 'e'}
差集 set6:
{'p', 'y', 'n'}
去除列表里重复元素 set7:
{555, 333, 111, 666, 444, 222}
Next Section
submitReset Code
ChapterCourseware