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

Basic knowledge of python (III)

編輯:Python

Python Basic knowledge of ( 3、 ... and )

    • 1. Sequence
    • 2. list
      • 2.1 Common methods of list objects
      • 2.2 List creation
      • 2.3 The addition of list elements
      • 2.4 Deletion of list elements
      • 2.5 List element access and counting
      • 2.6 Slicing operation
      • 2.7 Traversal of list
      • 2.8 Copy all elements of the list to the new list object
      • 2.9 Sort the list
      • 2.10 Summary of other built-in functions related to the list
      • 2.11 Multidimensional list
    • 3. Tuples tuple
      • 3.1 Tuple creation
      • 3.2 Element access and counting of tuples
      • 3.3 zip
      • 3.4 The generator deduces to create tuples

1. Sequence

  1. Stored in the sequence is the address of the integer object , Instead of the value of an integer object .
  2. Python The commonly used sequence structures in are : character string 、 list 、 Tuples 、 Dictionaries 、 aggregate

2. list

list : Used to store any number of 、 Any type of data set .
Standard syntax format for list definitions :a = [10,20,30,40]
The elements in the list can be different , It can be any type . such as :a = [10,20,‘abc’,True]

2.1 Common methods of list objects

Method The main points of describe list.append(x) Add elements Put the element x Add to list list The tail list.extend(aList) Add elements Will list alist All elements are added to the list list The tail list.insert(index,x) Add elements In the list list The specified location index Insert element at xlist.remove(x) Remove elements In the list list Delete the first occurrence of the specified element xlist.pop([index]) Remove elements Delete and return to list list Until specified index The element of , The default is the last element list.clear() Delete all elements Delete all elements of the list , Not to delete list objects list.index(x) Access elements Return to the first x Index position of , If it does not exist x Element throws an exception list.count(x) Count Returns the specified element x In the list list Is the number of times len(list) List length Returns the number of elements contained in the list list.reverse() Flip list All elements flip in place list.sort() Sort All elements are sorted in place list.copy() Shallow copy Returns a shallow copy of a list object

2.2 List creation

  • Basic grammar [ ] establish
>>> a = [10,20,'gaoqi','sxt']
>>> a = [] # Create an empty list object 
  • list() establish
    Use list() You can convert any iteratable data into a list .
>>> a = list() # Create an empty list object 
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = list("gaoqi,sxt")
>>> a
['g', 'a', 'o', 'q', 'i', ',', 's', 'x', 't']
  • range() Create a list of integers
    range([start], end ,[step])
    start Parameters : Optional , Represents the starting number . The default is 0
    end Parameters : Mandatory , Represents the ending number .
    step Parameters : Optional , Indicating step size , The default is 1
    python3 in range() Back to a range object , Not a list . We need to pass list() Method to convert it to a list object .
>>> list(range(3,15,2))
[3, 5, 7, 9, 11, 13]
>>> list(range(15,3,-1))
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4]
>>> list(range(3,-10,-1))
[3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  • Generate list by derivation
    Use for Circulation and if Statement to create a list
>>> a = [x*2 for x in range(5)] # Loop to create multiple elements 
>>> a
[0, 2, 4, 6, 8]
>>> a = [x*2 for x in range(100) if x%9==0] # adopt if Filter element 
>>> a
[0, 18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]

2.3 The addition of list elements

  • append() Method
    Modify the list object in place , It's true. Add a new element at the end of the list , The fastest , Recommended
>>> a = [20,40]
>>> a.append(80)
>>> a
[20, 40, 80]
  • + Operator operation
    Not really adding elements to the tail , It is Create a new list object ; Copy the elements of the original list and the elements of the new list into the new list object in turn . For manipulating a large number of elements,... Is not recommended
>>> a = [20,40]
>>> id(a)
46016072
>>> a = a+[50]
>>> id(a)
46015432 # Variable a The address of has changed , That is, a new list object is created .
  • extend() Method
    Add all elements of the target list to At the end of this list , It belongs to in-situ operation , Do not create new list objects
>>> a = [20,40]
>>> id(a)
46016072
>>> a.extend([50,60])
>>> id(a)
46016072
  • insert() Insert elements
    Use insert() Method can insert the specified element into the list object Set any position . This will move all elements behind the insertion position , It will affect the processing speed . When a large number of elements are involved , Avoid using . There are other functions like this movement :remove()、pop()、del(), When they delete non tail elements, they also move the elements behind the operation position
>>> a = [10,20,30]
>>> a.insert(2,100)
>>> a
[10, 20, 100, 30]
  • Multiplication extension
    Use multiplication to expand the list , Generate a new list , Multiple repetitions of the original list element when a new list element
>>> a = ['sxt',100]
>>> b = a*3
>>> a
['sxt', 100]
>>> b
['sxt', 100, 'sxt', 100, 'sxt', 100]
For multiplication operations , also : character string 、 Tuples . for example :
>>> c = 'sxt'
>>> d = c*3
>>> c
'sxt'
>>> d
'sxtsxtsxt'

2.4 Deletion of list elements

  • del Delete
    Delete the element at the specified position in the list
>>> a = [100,200,888,300,400]
>>> del a[1]
>>> a
[100,200,300,400]
  • pop() Method
    pop() Delete and return the specified location element , If no location is specified, the last element of the default action list
>>> a = [10,20,30,40,50]
>>> a.pop()
50
>>> a
[10, 20, 30, 40]
>>> a.pop(1)
20
>>> a
[10, 30, 40]
  • remove() Method
    Delete the first occurrence of the specified element , If the element does not exist, an exception is thrown
>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.remove(20)
>>> a
[10, 30, 40, 50, 20, 30, 20, 30]
>>> a.remove(100)
Traceback (most recent call last):
File "<pyshell#208>", line 1, in <module>
a.remove(100)
ValueError: list.remove(x): x not in lis

2.5 List element access and counting

Elements can be accessed directly by index . The interval of the index is [0, List length -1] This range . Beyond this range, an exception will be thrown

>>> a = [10,20,30,40,50,20,30,20,30]
>>> a[2]
30
>>> a[10]
Traceback (most recent call last):
File "<pyshell#211>", line 1, in <module>
a[10]
  • index() Gets the index of the first occurrence of the specified element in the list
    index() You can get the specified element Index position of the first occurrence .
    index(value,[start,[end]])
    among ,start and end Specifies the scope of the search .
>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.index(20)
1
>>> a.index(20,3)
5
>>> a.index(20,3) # From index location 3 The first thing to start searching later 20
5
>>> a.index(30,5,7) # From index location 5 To 7 This interval , First appearance 30 Position of elements 
6
  • count() Gets the number of times the specified element appears in the list
    count() You can return the number of times the specified element appears in the list .
>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.count(20)
3
  • len() Returns the length of the list
    len() Returns the length of the list , That is, the number of elements in the list .
>>> a = [10,20,30]
>>> len(a)
3
  • Membership judgment
    Determine whether the specified element exists in the list , We can use count() Method , return 0 It means that there is no , Return is greater than the 0 It means that there is . however , Generally, we will use more concise in Keyword to judge , Go straight back to True or False
>>> a = [10,20,30,40,50,20,30,20,30]
>>> 20 in a
True
>>> 100 not in a
True
>>> 30 not in a
False

2.6 Slicing operation

section slice Operation allows us to quickly extract sub lists or modify
[ Starting offset start : End offset end : step step]
notes : When the step size is omitted, the second colon can be omitted
(1) When three values are positive , Examples are as follows :

Operation and instructions Example result [:] Extract the entire list [10,20,30][:][10,20,30][start:] from start Index start to end [10,20,30][1:][20,30][:end] Know from the beginning end-1[10,20,30][:2][10,20][start:end] from start To end-1[10,20,30,40][1:3][20,30][start: end :step] from start Extract to end-1, Step length is step[10,20,30,40,50,60,70][1:6:2][20, 40,60]

(2) When three values are negative , Examples are as follows :

Operation and instructions Example result [10,20,30,40,50,60,70][-3:] The last three [50,60,70]10,20,30,40,50,60,70][-5:-3] From the penultimate to the penultimate ( The head is not the tail )[30,40][10,20,30,40,50,60,70][::-1] Step size is negative , Reverse extraction from right to left [70, 60, 50, 40, 30, 20, 10]

When slicing , The start offset and end offset are not [0, String length -1] This range , No errors reported
The starting offset is less than 0 Will be treated as 0, The end offset is greater than “ length -1” Will be treated as “ length -1”

>>> [10,20,30,40][1:30]
[20, 30, 40] # No report error 

2.7 Traversal of list

for obj in listObj:
print(obj)

2.8 Copy all elements of the list to the new list object

# Error model :
list1 = [30,40,50]
list2 = list1 # Just to list2 It also points to the list object , in other words list2 and list2 The holding address value is the same , The elements of the list object itself are not copied .
# Correct demonstration :
list1 = [30,40,50]
list2 = []

2.9 Sort the list

  • Modify the original list , Do not create a new sort of list
    a.sort() # The default is ascending
    a.sort(reverse=True) # Descending order
>>> a = [20,10,30,40]
>>> id(a)
46017416
>>> a.sort() # The default is ascending 
>>> a
[10, 20, 30, 40]
>>> a = [10,20,30,40]
>>> a.sort(reverse=True) # Descending order 
>>> a
[40, 30, 20, 10]
>>> import random
>>> random.shuffle(a) # Out of order 
>>> a
[20, 40, 30, 10]
  • Create a new sort of list
    We can also use built-in functions sorted() Sort , This method Return to the new list , Do not modify the original list
    a = sorted(a) # Default ascending order
    c = sorted(a,reverse=True) # Descending
>>> a = [20,10,30,40]
>>> id(a)
46016008
>>> a = sorted(a) # Default ascending order 
>>> a
[10, 20, 30, 40]
>>> id(a)
45907848
>>> a = [20,10,30,40]
>>> id(a)
45840584
>>> b = sorted(a)
>>> b
[10, 20, 30, 40]
>>> id(a)
45840584
>>> id(b)
46016072
>>> c = sorted(a,reverse=True) # Descending 
>>> c
[40, 30, 20, 10]
  • reversed() Return iterator
    Built in functions reversed() Reverse order is also supported , With list objects reverse() The difference is , Built in functions reversed() Don't make any changes to the original list , Just return an iterator object in reverse order
>>> a = [20,10,30,40]
>>> c = reversed(a)
>>> c
<list_reverseiterator object at 0x0000000002BCCEB8>
>>> list(c)
[40, 30, 10, 20]
>>> list(c)
[]

2.10 Summary of other built-in functions related to the list

  • max and min
    Used to return the maximum and minimum values in the list
  • sum
    Sum all elements of a numeric list , For non numeric list operation, an error will be reported

2.11 Multidimensional list

  • 2 d list
full name Age Salary City Gao Xiaoyi 1830000 Beijing Gao Xiaoer 1920000 Shanghai Gao Xiaowu 2010000 Shenzhen
>>>a = [
[" Gao Xiaoyi ",18,30000," Beijing "],
[" Gao Xiaoer ",19,20000," Shanghai "],
[" Gao Xiaoyi ",20,10000," Shenzhen "],
]
>>> print(a[1][0],a[1][1],a[1][2])
Gao Xiaoer 19 20000

3. Tuples tuple

Lists are variable sequences , You can modify any element in the list . Tuples belong to immutable sequences , Elements in tuples cannot be modified . therefore , Tuples do not add elements 、 Modifying elements 、 Delete element related methods
Tuples support the following operations :

  1. Index access
  2. Slicing operation
  3. Connection operation
  4. Membership operations
  5. Comparison operation
  6. Count : Tuple length len()、 Maximum max()、 minimum value min()、 Sum up sum()

3.1 Tuple creation

  • adopt () Creating a tuple . Parentheses can be omitted
    a = (10,20,30) perhaps a = 10,20,30
    If the tuple has only one element , Must be followed by a comma . This is because the interpreter will put (1) Interpreted as an integer 1,(1,) Interpreted as tuples
>>> a = (1)
>>> type(a)
<class 'int'>
>>> a = (1,) # perhaps a = 1, 
>>> type(a)
<class 'tuple'>
  • adopt tuple() Creating a tuple
    tuple( Objects that can be iterated )
    for example :
b = tuple() # Create an empty tuple object 
b = tuple("abc")
b = tuple(range(3))
b = tuple([2,3,4]

3.2 Element access and counting of tuples

  1. The element of a tuple cannot be modified
  2. The element access of tuples is the same as that of lists , It just returns the tuple object
>>> a = (20,10,30,9,8)
>>> a[1]
10
>>> a[1:3]
(10, 30)
>>> a[:4]
(20, 10, 30,9)
  1. List about sorting methods list.sorted() Is to modify the original list object , Tuples do not have this method . If you want to sort tuples , Only built-in functions can be used sorted(tupleObj), And create a new List objects
>>> a = (20,10,30,9,8)
>>> sorted(a)
[8, 9, 10, 20,30] # Tuples become lists after sorting 

3.3 zip

zip( list 1, list 2,…) Combine the elements at the corresponding positions of multiple lists into tuples , And return this zip object

>>> a = [10,20,30]
>>> b = [40,50,60]
>>> c = [70,80,90]
>>> d = zip(a,b,c)
>>> list(d)
[(10, 40, 70), (20, 50, 80), (30, 60,90)]

3.4 The generator deduces to create tuples

  1. The generator derivation is similar to the list derivation , Only the generator derivation uses parentheses . List derivation directly generates list objects , The generator derivation generates neither a list nor a tuple , It's a generator object
  2. We can use the generator object , Into a list or tuple . You can also use generator objects __next__() Method , Or use it directly as an iterator object
  3. No matter how you use it , After element access , If you need to revisit the elements , The generator object must be recreated
>>> s = (x*2 for x in range(5))
>>> s
<generator object <genexpr> at 0x0000000002BDEB48>
>>> tuple(s)
(0, 2, 4, 6, 8)
>>> list(s) # The element can only be accessed once . The second time is empty . It needs to be regenerated once []
>>> s
<generator object <genexpr> at 0x0000000002BDEB48>
>>> tuple(s)
()
>>> s = (x*2 for x in range(5))
>>> s.__next__()
0
>>> s.__next__()
2
>>> s.__next__()
4

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