程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python learning notes]-02-set set set

編輯:Python

List of articles

  • Preface
  • One 、 aggregate
    • 1. Definition
    • 2. Difference between set and list
    • 3. Set creation
    • 4. Simple use of collections
  • Two 、 Addition, deletion and modification of collection
    • 1.add function
    • 2.update function
    • 3.remove function
    • 4.clear function
    • 5.del function
    • 6. Important statement
  • 3、 ... and 、 Set operations Bad 、 hand over 、 and
    • 1. Get the difference set of two sets (difference function )
    • 2. Get the intersection of two sets (intersection function )
    • 3. Get the union of two sets (union function )
    • 4. Determine whether there are the same elements in the set (isdisjoint function )
  • summary


Preface

This section focuses on the introduction python The set in
Definition of set , The basic operation of a set , Common functions in Collections


Tips : The following is the main body of this article

One 、 aggregate

1. Definition

  • aggregate set Is an unordered sequence of non-repeating elements
  • It is often used to intersect and merge two lists
  • Sets are the same as lists , Supports all data types

2. Difference between set and list

function list aggregate The order Orderly disorder Content repeatable Do not repeat function For the use of data It is used to obtain the intersection, union and difference sets of data Indexes There is an index No index Symbol [] [1, 2, 3]{} {1, 2, 3}

3. Set creation

adopt set Function to create a collection , Out of commission {} To create an empty collection

a_set = set() # Empty set 
a_set = set([1, 2, 3]) # Pass in a list or tuple 
b_set = {
1, 2, 3} # Incoming elements 
c_set = {
} # Error definition ,{} The default is the dictionary 

4. Simple use of collections

case

# Simple use of collections 
a = set()
print(type(a))
b = set(['python', 'django', 'flask'])
print(b)
c = {
(1, 2, 3), '123', 1}
print(c)
d = {
}
print(d, type(d))
a_list = ['python', 'django', 'python', 'flask']
b_set = set(a_list)
print(b_set)

Running results
Collection needs attention b Instead of adding a list to a collection , Instead, you add elements from the list to the collection
d By default, dictionaries are created instead of collections

<class 'set'>
{
'django', 'python', 'flask'}
{
'123', 1, (1, 2, 3)}
{
} <class 'dict'>
{
'django', 'python', 'flask'}

Two 、 Addition, deletion and modification of collection

1.add function

Used to add an element to the collection , If the element already exists in the collection, the function does not execute
set.add(item)
item Elements to add to the collection
case:

a_list = ['python', 'django', 'django', 'flask']
a_set = set()
a_set.add(a_list[0])
a_set.add(a_list[1])
a_set.add(a_list[2])
a_set.add(a_list[-1])
print(a_set)
a_set.add(True)
a_set.add(None)
print(a_set)

Running results

{
'python', 'flask', 'django'}
{
True, 'django', 'flask', 'python', None}

The last element added to the set is not necessarily at the last edge of the set , Sets are unordered

2.update function

Add a new collection ( Or list 、 Tuples 、 character string ), If the elements in the new set exist in the original set, they will be ignored
set.update(iterable)
iterable: aggregate , List tuple string
case:

a_tuple = ('a', 'b', 'c')
a_set = set()
a_set.update(a_tuple)
print(a_set)
a_set.update('python')
print(a_set)

Running results :

{
'a', 'b', 'c'}
{
'h', 'c', 'o', 'n', 'a', 'b', 'y', 'p', 't'}

The elements in the string are broken up and added to the collection
have access to update Instead of a function add function
update Think of it as add The advanced version of , You can add more than one member at a time

3.remove function

Delete an element in the collection , If the element does not exist, an error will be reported
set.remove(item)
item: An element in the current collection , Be careful It's not an index , Set has no index

4.clear function

Empty all elements in the current collection
set.clear()
No parameter

5.del function

del Only the collection itself can be deleted directly

case:

a_set = set()
a_list = ['python', 'django', 'django', 'flask']
a_set.update(a_list)
print(a_set)
print('func remove')
a_set.remove('python')
print(a_set)
print('func clear')
a_set.clear()
print(a_set)
print('func del')
del(a_set)

Running results :

{
'python', 'flask', 'django'}
func remove
{
'flask', 'django'}
func clear
set()
func del

6. Important statement

  • The collection cannot get the element through the index
  • The collection cannot get any method of an element
  • A collection is just a temporary type used to handle lists or tuples , Not suitable for storage and transmission

3、 ... and 、 Set operations Bad 、 hand over 、 and

1. Get the difference set of two sets (difference function )

difference function
Returns the difference set of a set , That is, the returned set elements are contained in the first set , But not in the second set
a_set.diference(b_set)
b_set The current set needs to be compared
Return value : Returns the difference between the original set and the comparison set
case:

drivers = ['dewei', 'xiaomu', 'xiaoming', 'xiaoman']
testers = ['xiaomu', 'xiaoman', 'xiaogang', 'xiaotao']
dirver_set = set(drivers)
test_set = set(testers)
sinple_drivers = dirver_set.difference(test_set)
print(sinple_drivers)

Running results :

{
'xiaoming', 'dewei'}

2. Get the intersection of two sets (intersection function )

intersection function
Returns the elements contained in two or more collections
a_set.intersection(b_set…)
b_set…: Compared with the current set 1 One or more sets
Return value : Returns the intersection of the original set and the comparison set
case:

a = ['dewei', 'xiaomu', 'xiaohua', 'xiaoguo']
b = ['xiaohua', 'dewei', 'xiaoman', 'xiaolin']
c = ['xiaoguang', 'xiaobai', 'dewei', 'xiaoyuan']
a_set = set(a)
b_set = set(b)
c_set = set(c)
print(a_set, b_set, c_set)
res = a_set.intersection(b_set, c_set)
# Convert a collection to a list 
xiaotou = list(res)
print('{} It's a thief '.format(xiaotou[0]))

Running results :

{
'xiaomu', 'dewei', 'xiaohua', 'xiaoguo'} {
'xiaolin', 'dewei', 'xiaoman', 'xiaohua'} {
'dewei', 'xiaoguang', 'xiaoyuan', 'xiaobai'}
dewei It's a thief

3. Get the union of two sets (union function )

union function
Returns the union of sets , That is, it contains all the elements of the set , Repeated elements only appear once
a_set.union(b_set…)
b_set…: Compared with the current set 1 Or sets
case:

a_school = [' Half a day on Friday ', ' Free training on weekends ', ' Friday off ']
b_school = [' School hours start from 6 Point changed to 5 spot ', ' Leave less homework ', ' Change to a comfortable seat ']
c_school = [' Leave less homework ', ' Half a day on Friday ', ' Food improvement ']
a_set = set(a_school)
b_set = set(b_school)
c_set = set(c_school)
print(a_set, b_set, c_set)
help_data = a_set.union(b_set, c_set)
# help_data = a_set.union(b_school, c_school)
# The same function can be achieved by using the annotation section 
print(help_data)

Running results :

{
' Half a day on Friday ', ' Friday off ', ' Free training on weekends '} {
' Leave less homework ', ' School hours start from 6 Point changed to 5 spot ', ' Change to a comfortable seat '} {
' Food improvement ', ' Leave less homework ', ' Half a day on Friday '}
{
' Friday off ', ' Change to a comfortable seat ', ' Food improvement ', ' Leave less homework ', ' Half a day on Friday ', ' School hours start from 6 Point changed to 5 spot ', ' Free training on weekends '}

4. Determine whether there are the same elements in the set (isdisjoint function )

isdisjoint function
function : Determine whether two sets contain the same elements , If there is no return True, Otherwise return to False
usage :a_set.isdisjoint(b_set)
b_set: And the set used by the current set to judge
Returns a Boolean value
case:

# shortcoming , Can not contain 
ccompany_not_allow = {
' Woman ', ' Drink ', ' smoking ', ' sleep late '}
one_player = {
' male ', ' running ', ' Vigour ', ' Drink '}
two_player = {
' Woman ', ' routine ', ' Taekwondo '}
three_player = {
' male ', ' Taiji boxing '}
four_player = {
' male ', ' Karate ', ' young '}
print(ccompany_not_allow.isdisjoint(one_player))
print(ccompany_not_allow.isdisjoint(two_player))
print(ccompany_not_allow.isdisjoint(three_player))
print(ccompany_not_allow.isdisjoint(four_player))

Running results :

False
False
True
True

Used 5 A collection of , The main set is ccompany_not_allow, in addition 4 Sets correspond to 4 Personal characteristics

summary

Here is a summary of the article :
This article introduces the creation of collections , The difference between sets and lists , Common functions for adding, deleting and modifying sets and functions for set operations .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved