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

[Python] in depth explanation of sequences and dictionaries, necessary for review - too detailed

編輯:Python

List of articles :

    • Sequence
      • The concept of sequence
      • Standard type operators
      • Sequence type operators
      • Sequence slicing
        • Flip strings
      • Sequence built-in function
          • len function
          • max function -O(N)
          • min function -O(N)
          • sorted function
          • sum function
          • enumerate function
          • zip function
    • character string
      • The difference between the three quotation marks
      • Understand string " immutable "
      • Standard type operators for strings
      • Operators that apply only to strings
      • Original string (raw strings)
      • repr Functions and backquote operators
      • string Module common functions
        • Be careful : Remember that strings are immutable objects , Only new strings can be generated
          • join function
          • **split function **
          • **startswith function and endswith function **
          • strip function
          • ljust rjust center function
          • find function
          • **replace function **
          • **isalpha function and isdigit function **
          • **lower and upper function **
      • About Terminator
    • list []
      • Use the slice operator to access list elements
      • List common operations
        • append: Additional elements
        • Delete the specified subscript element del
        • Delete elements by value remove
        • List comparison operation
        • in/not in: Determine whether an element is in the list
        • Join operators (+): Connect two lists
        • extend: List connection
        • Repeat operator (*):
        • insert: Insert at any position
        • reverse: Flip the list in place
        • sort: In situ sorting
        • count: Count the number of elements
        • index: Equivalent to finding , Returns the subscript
        • pop: Delete an element of the list
          • Pay attention to the above functions :
      • List based stack
      • List based queues
      • A deep copy of the list / Shallow copy ( Selected studies )
        • summary :
        • How to make a deep copy :
    • Tuples ()
      • Tuples are commonly used
      • Default collection type
      • Understand the of tuples " immutable "
        • The reason why tuples cannot be replaced
    • Dictionaries {}
      • Create a dictionary
      • Visit the elements in the dictionary
      • Modify dictionary elements
      • Delete dictionary elements
      • Common built-in functions
        • in / not in:
        • len function
        • hash function
        • keys
        • values
        • items
    • aggregate (set)
      • Set basic operations
        • intersect & Combine | Difference set - Symmetric difference set ^
        • Data De duplication Use ->set

This article mainly explains the content :

understand Python The basic concept of the sequence of .
Mastering strings / list / Tuples / How to use a dictionary .
Understand the differences between lists and tuples and their application scenarios .
understand Python Deep and shallow copies in .
Understand the dictionary “ Key value pair ” This concept


Sequence

The concept of sequence

Contains several elements , The elements are arranged in order , One or more elements can be accessed by subscript . Such an object , Python It is uniformly called sequence (Sequence).

Python The following objects in are all part of the sequence

  • character string
  • list
  • Tuples

Same sequence , There are many similarities in their ways of use


Be careful : The order of the elements in the sequence is very important , Because the comparison is in order

a = [1,2,3]
b = [3,2,1]
print(a ==b) #False

Standard type operators

The following standard type operators , In most cases, it is applicable to sequence objects ( A few exceptions are , Elements saved in a sequence do not support standard type operators ).


Sequence type operators

  • in/not in: Determine whether an element exists in the sequence , Returns a Boolean value .
a = [1,2,3,4]
print(3 in a) #True
print(3 not in a) #False
  • Join operators (+): Connect two sequences of the same type .
a = [1,2,3,4]
b = [5,6]
print(a+b) # Return to a new list , Contains a and b All elements of [1, 2, 3, 4, 5, 6]
  • Join operators are often inefficient ( Create new objects , Copy the original object into ). For a list of , Recommended extend To do this ; For strings , Recommended join This way .
a = [1,2,3,4]
b = [5,6]
a.extend(b) # Is equivalent to b All elements of are inserted into a Behind 
print(a) #[1, 2, 3, 4, 5, 6]
  • Repeat operator (*): Repeat a sequence N Time .
a =[1,2,3]
print(a*3) #[1, 2, 3, 1, 2, 3, 1, 2, 3]

Sequence slicing

  • Slice operator ([ ], [A:B], [A:B:C]): Access one of these elements by subscript , Or some subsequence

  • positive The index starts at the beginning of the sequence , negative The index starts at the end of the sequence .
  • Trying to access an out of bounds index , Exception will be thrown ( It can be simply understood as program execution error )
a =[1,2,3]
print(a[100])
# Execution results :
IndexError: list index out of range

About slicing : Left closed right away Section

The way 1:[:] The left and right endpoints do not write values , What is intercepted is the elements of the entire sequence , From a to Z

a =[1,2,3,4,5]
print(a[:])#[1, 2, 3, 4, 5]

The way 2:[A:B]

Element subscript value range : [A,B)

a =[1,2,3,4,5]
print(a[1:3]) #[2,3] Intercept subscripts [1,3) The elements of 
print(a[1:-1]) #[2,3,4] Intercept subscripts [1,-1) The elements of 
print(a[:3]) #[1,2,3] Intercept subscripts [0,3) The elements of 
print(a[1:]) #[2,3,4,5] Intercept subscripts [1,-1) The elements of 

If the left endpoint does not write , The default from the 0 Start , The right endpoint does not write , The default is to intercept to the last position ( namely :-1 Location )


The way 3:[A:B:C] The third parameter represents the step size , That is, every few elements

  • Extend slice operation [::] In addition to representing the start and end positions of subsequences , It can also mean “ step ”

Example :

a = [1,2,3,4,5]
print(a[::2]) # Intercept one every two elements 
# Execution results :
[1,3,5]

Flip strings

String flip , This is a very basic , It is also a topic that often appears in the written examination interview . We have learned C/C++, There are three ways to solve this problem .

Method 1: Head and tail pointer

char str[] = "abcdefg";
char* beg = str;
char* end = str + strlen(str);
while (beg < end) {

swap(*beg++, *--end);
}

Method 2: Stack

char str[] = "abcdefg";
Stack stack;
char* p = str;
while(p) {

stack.push(*p++);
}
int index = 0;
while(!stack.empty()){

str[index++] = stack.top();
stack.pop();
}

Method 3: Use reverse + Iterator flip

#include <algorithm>
char str[] = "abcdefg";
std::reverse(str, str + strlen(str)); // Pointers are natural iterators 

python How to do it :

a = "abcdefg"
print(a[::-1])

The meaning of this code :

a[::-1] -1 It means to go forward , Take the elements from the back to the front

a = [1,2,3,4,5,6]
print(a[::-1]) #[6,5,4,3,2,1]
# meaning 
from -1 Position forward , Go to the subscript -1 Location , And then from 6 Start walking

For slicing grammar , It doesn't matter if the subscript is out of bounds . Because I took Before closed after opening Section , The elements in the interval , Take as much as you can
How many? .


Sequence built-in function

len function

len: Returns the length of the sequence .

a = [2,3,4,5]
print(len(a)) #4
b = "hello"
print(len(b)) #5

max function -O(N)

max: Returns the maximum value in the sequence

a = [2,3,4,5]
print(max(a)) #5
b = "helloz"
print(max(b)) #z

min function -O(N)

min: Returns the minimum value in the sequence

a = [2,3,4,5]
print(min(a)) #2
b = "helloz"
print(min(b)) #e

sorted function

sorted: Sort . This is a very useful function . Returns an ordered sequence ( Copy of input parameters ).

a = ['abc','acb','a','b']
print(sorted(a)) #['a', 'abc', 'acb', 'b']
a = [5,3,3,1,5]
print(sorted(a)) #[1, 3, 3, 5, 5]

sorted It can support self customized sorting rules


sum function

sum: Sum the elements in the sequence ( All elements in the sequence are required to be numbers )

a = [1,2,3,4,5]
print(sum(a)) #15
a= [1,'a']
print(sum(a)) # Report errors unsupported operand type(s) for +: 'int' and 'str'

enumerate function

enumerate: At the same time, the index and value of the sequence are listed You can avoid a lot of ugly code .

for example : Find the subscript of the element in the list

a = [1,2,3,4,5]
def Find(input_list,x):
for i in range(0,len(input_list)):
if input_list[i] == x:
return i
else: # Here else and for collocation 
return None
print(Find(a,2)) #1 Subscript to be 1

Here we use for Circular writing is not elegant enough , Use enumerate Function can be written gracefully

a = [1,2,3,4,5]
def Find(input_list,x):
for i ,item in enumerate(input_list):
if item == x:
return i
else: # Here else and for collocation 
return None
print(Find(a,2)) #1 Subscript to be 1

zip function

zip: The original meaning of this function is “ zipper ”,

x = [1,2,3]
y = [4,5,6]
z = [7,8,9,10] # Redundant 10 Don't ,3 That's ok 3 Column 
print(zip(x,y,z)) # Direct printing is an object id <zip object at 0x000001581CFE7748>
# Force the execution result to list, list 
print(list(zip(x,y,z))) #[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# Visual printing 
for i in zip(x,y,z):
print(i)
# Execution results :
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

zip It can be understood as row column interchange


zip A common usage of , Is to construct a dictionary

key = ('name','id','score')
value =('Mango','2022','99')
d = dict(zip(key,value)) # The execution result is converted into a dictionary 
print(d) # {'name': 'Mango', 'id': '2022', 'score': '99'}

character string

The difference between the three quotation marks

  • Python In single quotes (') String and double quotes (") Strings are equivalent . Unlike some programming languages ( such as Linux Shell), Escape characters are only valid in double quotes .
  • Python Use in “ Original string ” To accomplish such a function
  • Three quotes (‘’'/“”") Compared with the first two, the difference is , Can span multiple lines .
    • Three quotation marks can also be used as document strings

Understand string “ immutable ”

  • Strings are actually immutable objects . You can't change this string , Only one new string can be created .
a = 'abcd'
a[0] ='z' #TypeError: 'str' object does not support item assignment
a = 'z'+a[1:]
print(a) #zbcd

Standard type operators for strings

  • ==, !=, <, <=, >, >= The behavior of these operators has been mentioned earlier .

  • Remember that the size of string comparison is in dictionary order .

a = 'abc'
b = 'ab'
print(a != b) #True
print(a < b) #False Compare in dictionary order 

  • in/not in The rules of are consistent with the rules of the sequence .
a = 'abc'
print('a' in a) #True
print('z' in a) #False
  • Slicing is consistent with sequence rules
a = 'abcd'
print(a[1:2]) #b
print(a[:2]) #ab
print(a[1:]) #bcd
print(a[:]) #abcd
print(a[::2]) #ac

Operators that apply only to strings

  • %: Format replace .
x = 1
print('x = %d' %x) # x = 1

x = 10
y = 20
a = 'x = %d y = %d' %x # Lack of parameter : Report errors TypeError: not enough arguments for format string
# Positive solution :
x = 10
y = 20
a = 'x = %d y = %d' %(x,y)

Recommend writing : Prefixed f

x = 10
y = 20
a = f'x = {
x},y={
y}'
print(a) #x = 10,y=20

The following formatting strings are supported :


Original string (raw strings)

sometimes , We need to have \n Such characters are used as escape characters **. But sometimes we don't want to escape , Just the original **
\n As part of a string .

In the original string , Escape characters do not take effect

Example :QQ When sending messages , There is one “ Expression shortcut key ” The function of . This function is equivalent to “ Escape character ”.

When this function is enabled , Enter in the input box /se Will be replaced by an expression . For example, I send a directory to my colleagues /search/odin ( This originally meant linux A directory on )


In this case , We need to close “ Expression shortcut key ” function . about Python Come on , We can use the original string to solve this problem .


  • Add... Before the string literal r perhaps R Prefix , Represents the original string
print(r'hello \n world') #hello \n world

repr Functions and backquote operators

  • use str Function can convert some objects into strings . repr There's a similar effect .
a = 1
print(type(repr(a))) #<class 'str'> String type 
print(str('hello')) # hello
print(repr('hello')) # 'hello'

To sum up , str The converted string is for people to see . and repr Converted String , It's for Python The interpreter looks at it .

  • mean , repr The result is , It's actually a Python sentence , It can be directly put into the interpreter to execute ~

  • The quotation marks , and repr Function equivalence

string Module common functions

  • Python The standard library provides string modular , Contains many very convenient and practical functions

Be careful : Remember that strings are immutable objects , Only new strings can be generated





join function

Combine the strings in the sequence into one string . join function

a = ['aa','bb','cc']
b = ' '.join(a)
print(b) #aa bb cc

split function

Divide the string into a list by space split function

a = 'aa bb cc'
b = a.split(' ')
print(b) #['aa', 'bb', 'cc']

Usually and join Functions together

a = 'aaa,bbb,ccc'
b = a.split(',') # With , Split into lists 
print(b)
print(';'.join(b)) # Semicolon connection 
print('hello'.join(b))
# Execution results :
['aaa', 'bbb', 'ccc']
aaa;bbb;ccc
aaahellobbbhelloccc

startswith function and endswith function

Determine the beginning and end of the string startswith function and endswith function

a = 'hello world'
print(a.startswith('h')) #True
print(a.startswith('hee')) #False
print(a.endswith('d')) #True

strip function

Remove spaces at the beginning and end of a string / tabs strip function

Blank character : Space , Line break ,tab

a = ' hello world '
print(a.strip()) #hello world

Remove the blank characters on the left :lstrip

Remove the white space on the right : rstrip

a =' hello \n'
print(f'[{
a.lstrip()}]') # For the sake of convenience , add []
print(f'[{
a.rstrip()}]')
print(f'[{
a.strip()}]')
# Execution results :
[hello
]
[ hello]
[hello]

ljust rjust center function

Align left / Right alignment / Align in the middle ljust rjust center function

a = ' hello world'
print(a.ljust(30))
print(a.rjust(30))
print(a.center(30))
# Execution results :
hello world
hello world
hello world
find function

Find substring find function

a = ' hello world'
print(a.find('hello')) #4
a = 'hello hello '
print(a.find('h')) #0

Returns the first occurrence of the subscript

and in almost ,in The return is a Boolean value

a = ' hello world'
print(a.find('hello')) #4
print('hello' in a) #True

replace function

Replace substring ( Remember that strings are immutable objects , Only new strings can be generated ). replace function

a= 'hello world'
print(a.replace('world','python')) #hello python
print(a) #hello world Strings are immutable objects , Only new strings can be generated 

isalpha function and isdigit function

Determine whether the string is a letter / Numbers isalpha function and isdigit function

a = 'hello 1'
print(a.isalpha()) #False
a = '1234'
print(a.isdigit()) #True

lower and upper function

Convert case lower and upper function

a = 'Hello world'
print(a.lower()) #hello world
print(a.upper()) #HELLO WORLD

About Terminator

Did you learn C Language students , May ask , Python Whether or not the string of ‘\0’ And so on ?

  • Python There is no such thing as that annoying ‘\0’. Accurately speaking , about C language , Defects in the language itself do not support “ String type ”, To make do with character arrays . however Python There is no such burden at all .

list []

A string can only consist of characters , And immutable ; however The list can contain any type of object , More flexible to use .

Use the slice operator to access list elements

  • The slicing operation of the list is exactly the same as the string .
  • however Lists can also use slicing to modify elements .
a = [1,2,3,4]
a[0] = 100
print(a) #[100,2,3,4]

List common operations

append: Additional elements

hold append As an element

a = [1,2,3]
a.append('a')
print(a) #[1,2,3,'a']

Be careful : Use append: Is to insert elements as a whole

a = [1,2]
a.append([3,4]) # What is inserted is a whole 
print(a) #[1,2,[3,4]] 2 d list 
print(len(a)) #3

Delete the specified subscript element del

a = [1,2,3]
del(a[0])
print(a) #[2,3]

Delete elements by value remove

a = [1,2,3]
a.remove(1)
print(a) #[2, 3]
# If the element does not exist , You're going to report a mistake 
a.remove(4) # Report errors ValueError: list.remove(x): x not in list

List comparison operation

== != To determine that all elements are equal , The list is equal ;

< <= > >= Two lists start with the first element Compare in turn , Until one side wins . Compare... In order

a = ['abc',12]
b = ['acb',123]
c = ['abc',11]
print(a<c) #False
print(b<c) #False
print(b >c and a > c) #True
a = [1,2,3]
b = [3,2,1]
print(a <b) #True In order ratio 
a = [1,2,3]
b = ['a','b']
print(a<b) # Report errors :TypeError: '<' not supported between instances of 'int' and 'str'

in/not in: Determine whether an element is in the list

Time complexity O(N)

a = [1,2,3,'a']
print('a' in a) #True
print(4 in a) #False

Join operators (+): Connect two lists

a and b All the same , Generate new objects

a = [1,'a']
b = [2,'b']
print(a+b) #[1, 'a', 2, 'b']

extend: List connection

If you use append: Is to insert elements as a whole

a = [1,2]
a.append([3,4]) # What is inserted is a whole 
print(a) #[1,2,[3,4]] 
print(len(a)) #3

Use extend

Can be interpreted as += ( List does not support += Operator )

a = [1,2]
a.extend([3,4])
print(a) #[1,2,3,4]
print(len(a)) #4

Repeat operator (*):

a = [1,2]
print(a*3) #[1, 2, 1, 2, 1, 2]

insert: Insert at any position

If the subscript is large , Insert at the back

insert no return value :

a =[1,2,3]
print(a.insert(0,0)) #None

Example :

a=[1,2,3]
a.insert(0,0) # stay 0 Insert at subscript position 0
a.insert(100,100) # In subscript 100 Position insert 100
print(a) #[0, 1, 2, 3, 100]

reverse: Flip the list in place

a = [1,2,3,'ac']
a.reverse()
print(a) #['ac', 3, 2, 1]

You can also flip by slicing a[::-1] and reverse The difference between flipping :

Slice flipping does not modify the original object , Generate new objects , reverse Flip to modify the original object


sort: In situ sorting

This is the built-in member function of the list , and sorted Different

for example , Sort . When we talked about the sequence , There is a built-in function sorted, sorted A new ordered sequence is generated . The list itself has a member function sort, Is based on their own modifications , No new objects are generated .

a = [4,3,2,1]
sorted(a)# Built-in functions sorted
print(a)#[4, 3, 2, 1] a Don't change 
a.sort()# Member functions sort
print(a)#[1, 2, 3, 4]
a.sort(reverse=True) # Flip 
print(a) #[4,3,2,1]

About sort Method , By default, the derived algorithm of merge sort is used . The time complexity is O(N*log(N))


count: Count the number of elements

a = [4,3,2,1,2,4,2]
print(a.count(2)) # 3
print(a.count(5)) # 0

index: Equivalent to finding , Returns the subscript

a = [4,3,2,1]
print(a.index(4)) #0
print(a.index(5)) # Report errors ValueError: 5 is not in list

pop: Delete an element of the list

Subscript delete , The default value is -1, Delete the last element

If the list is empty, it will pop up , You're going to report a mistake

a =[1]
print(a) #[1]
a.pop()
print(a) #[]
a.pop() # If the list is empty, it will pop up , Report errors :IndexError: pop from empty list

You can also delete the subscript : If the subscript is out of bounds, an error will be reported

a = [1,2,3,4]
a.pop(3) # Delete the subscript as 3 The elements of 
print(a) #[1,2,3]
a.pop(6) # Report errors IndexError: pop index out of range

Pay attention to the above functions :

The list itself is a mutable object , So some methods are Modify your own , The method in this case does not return a value ,

This and the string operation must generate a new object , Is not the same .


List based stack

Let's review... In the data structure Stack , This is a kind of Last in, first out Data structure of . You can easily use lists to simulate

a = [] # An empty list 
a.append(1) #push operation Insert an element at the top of the stack 
print(a[-1]) #top operation Get the stack top element 
a.pop() #pop operation Pop up top element 

List based queues

Let's review... In the data structure queue , This is a kind of fifo Data structure of . You can also easily use list emulation

a = [] # An empty list 
a.append(1) #push operation Insert elements at the end of the queue 
print(a[0]) #top operation Get the team leader element 
a.pop(0) #pop operation Pop team leader element 

A deep copy of the list / Shallow copy ( Selected studies )

# Define a list object a.
a = [100, [1, 2]]
# be based on a, Created in three ways b, c, d
b = a
c = list(a)
d = a[:]
print(id(a), id(b), id(c), id(d)) #a and b Same as ,c,d Different b and a It's actually the same object . and c and d Are new list objects .
a[0] = 1
print(a, b, c, d) #a and b be affected c and d Unaffected 
a[1][0] = 1000
print(a, b, c, d) # All four are affected 
print(id(a[1]), id(c[1]), id(d[1])) # All the same 
# Execution results 
140541879626136 140541879626136 140541879655672 140541879655744
[1, [1, 2]] [1, [1, 2]] [100, [1, 2]] [100, [1, 2]]
[1, [1000, 2]] [1, [1000, 2]] [100, [1000, 2]] [100, [1000, 2]]
139973004362816 139973004362816 139973004362816

The result is a little complicated , Let's analyze it bit by bit

  • Define a list object a.
  • be based on a, Created in three ways b, c, d
  • First you can see , b and a It's actually the same object . and c and d Are new list objects .
  • modify a[0] You can see , a and b The values of are affected . however c and d Unaffected , because a and b Is the same object c and d It's a new object
  • Revise a[1][0]=1000 At this time, I was surprised to find , c and d The content of has also been affected !!!
  • At this time we guess , a, c, d The subscript of is 1 List elements of , In fact, they are the same object . Print out id, Proved our guess .


summary :

  • List assignment (=) No new object created , however list Both factory functions and slicing operations create new list objects .
  • Assignment of the list (=), Slicing operation ([:]), list Factory function , object Internal elements It's all going on Shallow copy .
  • Shallow copy means , Although I recreated a new object , But the new object contains child objects , It is the same object as the original sub object .
  • Deep copy means , Recreated a new object , At the same time, the children of this new object , It is also the re creation of a new deep
    Copy the object .
  • Deep copy through copy.deepcopy To complete

How to make a deep copy :

Be careful : Deep copy Can only be used for mutable objects

Make a deep copy : Import required copy modular

import copy
a = [100, [1, 2]]
b = copy.deepcopy(a)
print(id(a[1]), id(b[1]) )
# Execution results 
139818205071552 139818205117400

This time we see , a[1] and b[1] Is no longer an object .

  • Not just lists , Other containers , For example, tuples , Dictionaries , There are similar deep and shallow copy problems . The principle is the same as the list
  • It should be noted that , and It is not necessary to call deepcopy The deep copy will be executed , Python The interpreter itself will depend on the specific situation , such as Some situations are not suitable for deep copy , Deep copy will not be triggered .

import copy
a = (100, 'aaa')
b = copy.deepcopy(a)
print(id(a[0]), id(a[1]), id(b[0]), id(b[1]))
# Execution results 
6783664 140700444542616 6783664 140700444542616

Think about why ?

The purpose of making a deep copy : Prevent one of the data from changing , Will affect the results of other data

Deep copy is to change one to another , But if it's an immutable object , No modification is allowed , There are no requirements ,

Because the contents of tuples cannot be modified , Deep copy is not necessary !


Tuples ()

Many operations of tuples are consistent with lists . The only difference is that the contents of tuples are read-only .

Tuples are commonly used

Slicing operation : Same as list

Comparison operator , The rules are the same as the list

Connection operation (+), Repeat (*), Determine whether the element exists (in/not in) Are the same as the list .

** Because tuples are immutable , So it doesn't support append, extend, sort,[], And so on .** Yes, of course , Deep copy is not supported


Default collection type

  • All multiple objects , Separated by commas , In fact, they are tuples

Recall the awesome code we used to exchange the values of two elements .

x, y = y, x

Actually , x, y It's a tuple . adopt y, x This tuple creates a new tuple

x = 1
y = 2
x,y = y,x
print(type((x,y))) #<class 'tuple'>

Understand the of tuples “ immutable ”

  • Of a tuple “ immutable ” Refers to the of each element of a tuple id immutable . That is to say A tuple contains several objects , Then you can't add or delete any object to the tuple , You can't change one object to another .
  • If... In a tuple Some element , It's a mutable object ( Like lists or dictionaries ), Then it can still be modified .
a = ([1,2],[3,4])
a[0][0] = 100
print(a) #([100, 2], [3, 4])

Tuples : use , Commas separate elements

a = (10) # Because it could be (10+2)*2 This expression , therefore a Is an integer , It's not a tuple 
print(type(a)) #<class 'int'>
a = (10,2)
print(type(a)) #<class 'tuple'>

Be careful :

The tuple repetition operator is used here (*) The concept of .

a = (10+20,) *3 # There is no comma here ,a Namely 90
print(a) #(30, 30, 30)
print(type(a)) #<class 'tuple'> Tuples 

“ immutable ” It's really necessary ? If we just use a list , Can you cope with all application scenarios ?

The answer is No . since Python The designer of provides the object of tuple , Then there must be some cases , Only tuples can do , But the list is not up to it .

The reason why tuples cannot be replaced

reason 1: Using tuples when passing parameters to a function can avoid modifying the contents outside the function

You have a list , Now you need to call a API Do some processing . But you don't specifically confirm this API Whether it will mess up your list data . So it's much safer to pass a tuple at this time .

a = [1,2,3]
def func(input_list):
input_list[0] = 100
func(a)
print(a) #[100,2,3] The list can be modified 
# If you use tuples :
a = (1,2,3)
def func(input_list):
input_list[0] = 100
func(a) # Report errors :TypeError: 'tuple' object does not support item assignment
print(a)

reason 2: Tuples are hashable , Tuples can be used as a dictionary key, And the list is variable , A list cannot be used as a dictionary key

The dictionary we're going to talk about , Is a key value pair structure . The key of the dictionary must be “ can hash object ” ( A dictionary is essentially a hash surface ). And one can hash The premise of an object is immutability . Therefore, tuples can be used as keys of dictionaries , But the list doesn't work .

a = (1,2,3)
b = {

a:100
}
print(b) # {(1, 2, 3): 100}
# If it's a list : Report errors 
a = [1,2,3]
b = {

a:100 #TypeError: unhashable type: 'list'
}
print(b)

Dictionaries {}

Python The dictionary is a mapping type of data . The data is Key value pair . Python Our dictionary is based on hash Table implementation .

  • key (key): The key of the dictionary is the only ( One There cannot be two identical keys in a dictionary object ). meanwhile The key of the dictionary must be hash Of ( Can calculate a fixed hash value )
  • value (value): Dictionary There is no limit to the value . Numbers , character string , And other containers , Can be used as the value of the dictionary

Be careful : The types of keys and values of the dictionary , It doesn't need to be the same

Different key values use , Comma split

a = {

10:20,
'key':'value',
'a':True
}
print(a) #{10: 20, 'key': 'value', 'a': True}

Dictionary key Must be hashable , Immutable is changeable hash Necessary conditions

  • have access to hash() Function to determine whether hashing is possible
print(hash((10,20))) # Tuples can be hashed 3713074054217192181
print(hash([1,2])) # List cannot be hashed Report errors :TypeError: unhashable type: 'list'

Create a dictionary

  • Use { } Methods
a = {
'name':"Mango",'age':20}
print(a) #{'name': 'Mango', 'age': 20}
  • Use factory methods dict

    use Tuples as parameters , Each parameter of a tuple is a list , There are two values in the list : One is the key. One is the value.

a = dict((['name',"Mango"],['age',20]))
print(a) #{'name': 'Mango', 'age': 20}

  • Use the built-in method of Dictionary fromkeys
a = {
}.fromkeys(('name',"Ename"),"Mango")
print(a) #{'name': 'Mango', 'Ename': 'Mango'}
a = {
}.fromkeys(('name'),"Mango")
print(a) #{'n': 'Mango', 'a': 'Mango', 'm': 'Mango', 'e': 'Mango'}

Be careful : The types of keys and values of the dictionary , It doesn't need to be the same .


Visit the elements in the dictionary

  • Use [] You can get the value of the element .
    • Be careful : Key is a string , So the access is also in string form
a = {
'name':"Mango",'age':20}
print(a['name']) #Mango
print(a['age']) #20
  • for Loop through the elements in the dictionary
a = {
'name':"Mango",'age':20}
for item in a: #item Equivalent to each key 
print(item,a[item]) # Print key and value 
# Execution results :
name Mango
age 20

Be careful : Key value pairs in the dictionary , The order is uncertain ( memories hash The data structure of the table , There is no demand for key Orderly ).


Modify dictionary elements

Use [] You can add / Modify dictionary elements . -> If key non-existent , Will add ; If it already exists , Will modify .

a = {
} # An empty dictionary 
a['name'] ="Mango"
print(a) #{'name': 'Mango'}
a['name'] = "Lemon"
print(a) #{'name': 'Lemon'}

Delete dictionary elements

  • Use del To delete a key value pair
a = {
'name':"Mango",'age':20}
del a['name']
print(a) #{'age': 20}
  • Use clear Method , Clear all key value pairs in the whole dictionary
a = {
'name':"Mango",'age':20}
a.clear()
print(a) #{} An empty dictionary 
  • Use pop function , Delete key value pair , Get the value at the same time
a = {
'name':"Mango",'age':20}
b = a.pop('name')
print(a) # {'age': 20}
print(b) # Mango

Be careful : Dictionaries are also variable objects . But the key value is right key It can't be modified



Common built-in functions

in / not in:

** Decide on a key Is it in the dictionary ** ( The judgment is key, No value)

a = {
'name':"Mango",'age':20}
print('name' in a) #True
print('Mango' in a) #False

len function

len: The number of key value pairs in the dictionary

a = {
'name':"Mango",'age':20}
print(len(a)) #2

hash function

hash: Determine whether an object can hash. If you can hash, Then return to hash After that hashcode. Otherwise, it will run wrong .

print(hash(())) #3527539 Tuples are immutable , Can hash 
print(hash([])) #TypeError: unhashable type: 'list' List variable , Do not hash 

keys

Return a list , Contains all the of the dictionary key

a = {
'name':"Mango",'age':20}
print(a.keys()) #dict_keys(['name', 'age'])

values

Return a list , Contains all of the value

a = {
'name':"Mango",'age':20}
print(a.values()) #dict_values(['Mango', 20])

items

Return a list , Every element is a tuple , Contains key and value

a = {
'name':"Mango",'age':20}
print(a.items()) #dict_items([('name', 'Mango'), ('age', 20)]) 

aggregate (set)

A collection is a data structure implemented based on a dictionary . The set data structure realizes many intersection in mathematics , Combine , Difference set and other methods , It is very convenient to perform these operations .

Be careful !! Master assembly operation , For our follow-up exam questions, interview questions , Will be of great help .


Set basic operations

Sets and lists are different , The order of the set has no effect

a = set([1,2,3])
b = set([3,2,1])
print(a == b) #True
print(a,b) #{1, 2, 3} {1, 2, 3}

intersect & Combine | Difference set - Symmetric difference set ^

a = set([1, 2, 3])
b = set([1, 2, 3, 4])
print(a & b) # intersect 
print(a | b) # Union and collection 
print(b - a) # Take the difference set 
print(a ^ b) # Take the symmetric difference set ( Item in a In or in b in , But not both a and b in )
# Execution results 
{
1, 2, 3}
{
1, 2, 3, 4}
{
4}
{
4}

Data De duplication Use ->set

a =set( [1, 1, 2, 2, 3, 3])
print(a) #{1,2,3}
a = [1,2,1,11,1,1,2]
b = set(a)
print(a) #[1, 2, 1, 11, 1, 1, 2] 
print(b) #{1, 2, 11}

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