search
HomeBackend DevelopmentPython TutorialDetailed explanation of set syntax in python3

Detailed explanation of set syntax in python3

May 03, 2017 pm 03:45 PM
python3set

This article mainly summarizes the relevant information about the syntax of set (set) in python3. The article gives detailed sample code, which has certain reference value for everyone. Friends who need it can take a look below.

Introduction

set Gu Mingsiyi is a set, and the elements of the set are unique and unordered. Putting some elements in a { ​​} forms a set. The set can be of multiple data types (but not lists, sets, dictionaries, but can be tuples)

A set is an unordered non-repeating element of sets. Basic functionality includes relationship testing and elimination of duplicate elements. Set objects also support mathematical operations such as union, intersection, difference and sysmmetric difference.

Braces or the set() function can be used to create a set. Note: To create an empty collection, you must use set() instead of {}. {} is used to create an empty dictionary;

The specific syntax is summarized as follows.

add (add elements)

name = set(['Tom','Lucy','Ben'])
name.add('Juny')
print(name)

#输出:{'Lucy', 'Juny', 'Ben', 'Tom'}

clear (clear all elements)

name = set(['Tom','Lucy','Ben'])
name.clear()
print(name)

#输出:set()

copy (copy set collection)

name = set(['Tom','Lucy','Ben'])
new_name = name.copy()
print(new_name)

#输出:{'Tom', 'Lucy', 'Ben'}

difference (return Different elements in two or more sets and generate a new set)

A = set([2,3,4,5])
B = set([3,4])
C = set([2])
n = n1.difference(n2,n3)
print(n)

#输出:{5}
#返回A集合里面,在B和C集合中没有的元素,并生成新的集合

difference_update (Delete the elements in set A that exist in set B.)

A = set([2,3,4,5])
B = set([4,5])
A.difference_update(B)
print(A)

#输出:{2, 3}

discard (move Remove elements)

n = set([2,3,4])
n.discard(3)
print(n)

#输出:{2, 4}

intersection(Get the intersection and generate a new set)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n = n1.intersection(n2)
print(n)

#输出:{4, 5}

intersection_update(Get the intersection and modify the original set)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n1.intersection_update(n2)
print(n1)

#输出:{4, 5}

isdisjoint(Judge the intersection, Returns False if yes, True if not)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
print(n1.isdisjoint(n2))

#输出:False

issubset(Judge subset)

A = set([2,3])
B = set([2,3,4,5])
print(A.issubset(B))

#输出:True
#A是B的子集

issuperset(Judge parent set)

A = set([2,3])
B = set([2,3,4,5])
print(B.issuperset(A))

# 输出:True
#B是A的父集

pop(Randomly remove an element)

n = set([2,3,4,5])
n1 = n.pop()
print(n,n1)

# 输出:{3, 4, 5} 2

remove(remove the specified element)

n = set([2,3,4,5])
n.remove(2)
print(n)

# 输出:{3, 4, 5}

symmetric_difference(take the intersection and generate a new set)

A = set([2,3,4,5])
B = set([4,5,6,7])
print(A.symmetric_difference(B))

# 输出:{2, 3, 6, 7}

symmetric_difference_update(take the intersection and change the original set)

A = set([2,3,4,5])
B = set([4,5,6,7])
A.symmetric_difference_update(B)
print(A)

# 输出:{2, 3, 6, 7}

union (take the union and generate a new set)

A = set([2,3,4,5])
B = set([4,5,6,7])
print(A.union(B))

# 输出:{2, 3, 4, 5, 6, 7}

update (take the union and change the original set)

A = set([2,3,4,5])
B = set([4,5,6,7])
A.update(B)
print(A)

# 输出:{2, 3, 4, 5, 6, 7}

Summary

The above is the detailed content of Detailed explanation of set syntax in python3. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment