[Python] set set ① ( set definition | set features | code example - set definition )





1. Collection Features



The list/tuple/string data container was introduced in the previous blog,

  • After the list supports definition, add elements/modify elements/delete elements, and duplicate/ordered elements can be stored in the list;
  • After the tuple is defined, it is not possible to add elements/modify elements/delete elements, and tuples also support repeated/ordered elements;

Both lists and tuples are repetitive and ordered data containers. If you want to store non-repeatable data containers in the data container, you cannot use these two data containers;

This blog introduces a new data container with deduplication function: "Collection", the elements in the collection data container cannot be repeated;





2. Collection definition



Sets {}are ;

  • Define the collection data container literal; if there are repeated elements in it, the previous repeated elements will be automatically deleted, and the last element will be kept;
{
    
    元素1, 元素2, 元素3}
  • Define the collection data container variable; if there are repeated elements in it, the previous repeated elements will be automatically deleted, and the last element will be kept;
集合变量 = {
    
    元素1, 元素2, 元素3}
  • define an empty collection data container;
集合变量 = set() 

Note: If there are duplicate elements in the collection, the latter elements will be kept, and the former elements will be automatically deleted;


Review how the centralized data container is defined:

  • List: use square brackets []to define ;
  • Tuple: use parentheses ()to define ;
  • String: use double quotes ""to define ;
  • Collections:{} defined using curly braces ;




3. Code example - collection definition



In the following collections, collection literals/collection variables/empty collections are defined respectively;

When defining the collection variable, two repeated elements 'Tom' strings are defined,

{
    
    "Tom", "Jerry", "Jack", "Tom"}

Since the elements in the collection data container cannot be repeated, in the collection, one of the two Tom strings needs to be deleted, here the first Tom string is deleted, and the second Tom string is retained;

Code example:

"""
集合 代码示例
"""

# 定义集合字面量
{
    
    "Tom", "Jerry", "Jack"}

# 定义集合变量
names = {
    
    "Tom", "Jerry", "Jack", "Tom"}
# 上述集合中有两个 Tom 字符串, 由于 集合 不能重复, 第一个 Tom 字符串被删除
print(f"names = {
      
      names}, type = {
      
      type(names)}")
# 输出: names = {'Jack', 'Jerry', 'Tom'}, type = <class 'set'>

# 定义空集合
empty = set()
print(f"empty = {
      
      empty}, type = {
      
      type(empty)}")
# 输出: empty = set(), type = <class 'set'>

Results of the :

names = {
    
    'Tom', 'Jerry', 'Jack'}, type = <class 'set'>
empty = set(), type = <class 'set'>

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131108614
set
set