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

Python from introduction to project practice -- sequence

編輯:Python

List of articles

`


`

List of articles

  • List of articles
  • Preface
  • One 、 Preliminary understanding of sequence
    • One 、 list
            • List basic definitions
            • Detailed use of index
            • Data fragmentation
            • member operator
            • List manipulation functions
            • Detailed explanation of list related operations
    • Tuples
            • Multiplication and addition of tuples
          • Sequence statistical function
        • character string
          • Fragment operation of string
            • Reasons for garbled code in the process of string splitting
            • Simple string operation understanding
          • String formatting
            • String manipulation functions
          • Dictionaries
            • The basic use of dictionaries
            • Iterative output of dictionary
            • Dictionary operation function
  • summary

Preface

` I learned from the front Python Program logic structure in , stay Pytho Sequence knowledge is added in , Now? , We will learn Python The more important knowledge sequence in , And more in-depth explanation of string processing .


One 、 Preliminary understanding of sequence

seeing the name of a thing one thinks of its function , From the literal meaning, we can know that a sequence is an ordered set of classes , Through the sequence, we can not only save multiple data , You can also access the data in the sequence in the same way , The most important thing is , Sequence can use the concept of slice to obtain the data of some subsequences , stay Python in , list , Tuples , Dictionaries , Strings form the concept of sequences .

One 、 list

list (list) Is a common sequence type ,Python In addition to saving multiple data in the list , You can also dynamically modify the list data .

List basic definitions

stay Python in , The definition of list also adopts the method of assignment , However, the form is a little different from the previous assignment of variables . He used one [] Number .
for example :

infors=["i like you","Python","Hello word"]
#infors It's a list , It has three elements , Namely "i like you" ,"Python","Hello word".
# If we want to get one of these elements , Then we use index to get , and c Arrays in language are very similar . The range of the index is
#0~( List length -1)

Let me use an example to illustrate the index :

# Relevant knowledge points about list index
infors=["I like ","Python ","c++ is better than this","But i think " ] # Defines a list
# Sort the above words through a simple index
item=infors[0]+infors[1]+infors[3]+infors[2] # stay c++ and python in , Strings can be added
print(item) # Output the sorted statement
#python Index and c Arrays are very similar in language , however , The index can be inverted
del item
item=infors[-4]+infors[-3]+infors[-1]+infors[-2]
print(item)
# Looking at the running results of the two statements, we can find that the results of the two statements are exactly the same .
# When we are indexing , How to get the length of the list ? If you just count , It will undoubtedly increase the difficulty of our work ,Python A function is provided to calculate the length len();
print(len(infors))
print(type(infors)) # Get the type of list

We used many library functions in the above program , Let's first introduce these functions :

Function name

function

id()

Get the storage address of the variable , Usually a string of numbers

ord()

Get the ASCII Code value

type()

Get the type of variable , It's usually a string type

str()

When non string and string are used together , Convert a non string to a string

Just introduce these functions for the time being , I'll introduce it in detail later .
Index map :

Detailed use of index

(1). Iterate through the index to process the sequence
use len() Function to get the length of the sequence , And then through for loop , utilize range Get every element in the sequence . Of course , We can also change the data by indexing the elements in the sequence . Unlike tuples , The capacity of the list can be changed , Two tuples cannot , But they all support multiplication .
eg:

# coding:UTF-8
infors=["I like Pthon","and i like c++"," I am a freshman ",20," Like programming "] # Note that commas must be English symbols , Easy to confuse
# Index iteration
for item in range(len(infors)):
print(item,end=",")
# Multiplication of sequences
infors*=3 # Concise operator , I'll talk about it later
print(" The list tripled is :",infors)
# Leave the list empty
infor=[None]
print("%s" % type(infor))
Data fragmentation

There are often many data classes in a list , In addition to obtaining data class content by index , We can also extract a piece of data in the list through some operations , This is called slicing .
The illustration :

Fragment index format :
Antithetic image ( list )[ The starting position : Termination position : step ]
perhaps
object ( list )[ The starting position , Termination position ]
Program instance :

infors=["A","B","C","D","E","F","G","H","I","J","K","L"]
number_a=infors[3:7]
print(" The class content intercepted for the first time is :",number_a)
number_b=infors[-3:-8]
print(" The data class of the second interception is :",number_b)
# Realize list fragmentation through shortcuts
# Get index 3 In the future
print(infors[3:])
# Get index 7 All previous data
print(infors[:7]) # When the step size is not set , The default step size of the system is 1
# Set the interception step
number_size=infors[:7:2]
print(" In steps of 2 The index of :",number_size)


Of course, the operation of indexing is not just as listed above , There are many ways , In the actual development process , Operate by yourself as needed .

member operator

Operator

describe

in

Determine whether the data is in the list

not in

Determine whether the data is not in the list

List manipulation functions

function

describe

append()

Add a new class content after the list

clear()

Clear list data

copy()

Copy list

count(data)

Count the number of times a certain data appears in the list

extend( list )

Append a new list after the list

index(data)

Find the location of the first occurrence of a certain data from the list

insert(index,data)

Append new data to the specified position in the list

pop(index)

Pop up a data from the list and delete

remove(data)

Delete the data specified in the list

reverse()

List data inversion

sort()

Sort the list

Program instance :

infors=[1,2,3,4,5,6,7,8,9,10]
infors.append(11) # Add new class content
print(infors)
infor=infors.copy() # Copy list
print(infor)
num=infors.count(1) # Calculation 1 Number of occurrences
print(num)
infors.extend(infor) # Add a new list
print(infors)
index=infors.index(8) #8 Position of appearance
print(index)
infors.remove(3) # Delete 3
print(infors)
infors.reverse() # Inverse list
print(infors)
infors.sort() # Sort
print(infors)
infors.clear()# Clear the list
del infors

Detailed explanation of list related operations

(1).pop function ,clear Functions and remove Difference of function ,clear Function can be understood literally , Clear function , Then all data elements in the whole list will be deleted ,pop function , In data structure , This will be used by the bomb stack , Indicates that an element pops up , That is, take this data from the list , That is, the function return ,remove What is deleted is all a specific value in the list .

Lists can also be compared in size , If the two are equal , Then return to True, Otherwise , return False, If the data among them are the same , But if the order is different , It's also False.

Tuples

Tuples (Tuple) Is a linear data structure similar to a list , Unlike the list , The definition class content in tuples cannot be modified , And the dynamic expansion of capacity . Tuples are defined by “()” To achieve .

# coding:UTF-8
infors=("Pyhton","I like you","i will study you") # Define tuples
for item in infors:
print(item,end=",")
'''
remember , Tuples cannot be modified , Otherwise, an error will be reported , But tuples can be multiplied and added . If the tuple we define has only one element , Just add a comma after it , Indicates that the object is a tuple , Otherwise, it is a general variable .
'''
Multiplication and addition of tuples

The reason for explaining tuple operation separately here is because , Many people will have an illusion here , The characteristic of tuples is that the content cannot be modified , But we used multiplication , This is because multiplication is also good , Addition is also good , The contents of tuples are not modified at all , Just create another tuple with one tuple .

infors=(1,2,3,4,5,6,7,8)
# When using multiplication , You need a tuple to receive , Cannot add on the original basis ,
# If it is direct output , The system will output the returned data
print(infors)
print(infors*3)

Sequence statistical function

Lists and tuples will be used for data storage in project development , And the list data can be dynamically configured . Therefore, there is often a lot of data to be processed in the sequence , If you need to write your own function to implement each processing , It will undoubtedly increase the workload of programmers , therefore ,Python Some common sequence processing functions are provided .

function

describe

len()

Get sequence length

max()

Get the maximum value of the sequence

min()

Get the smallest value of the sequence

sum()

Get the sum of all values in the sequence

any()

There is one in the sequence True, Then for True, otherwise , by False

all()

All the contents in the sequence are True When , Only then True

Code example :

numbers=[1,2,3,4,5,6,5,4,3,2,1] # Definition list
print(" Element number :%d" % (len(numbers))) # Count the number of elements in the sequence
print(" Maximum value in the list :%d" % (max(numbers)))
print(" The smallest value in the list :%d" % (min(numbers)))
print(" The sum of all elements in the list :%d" % (sum(numbers))) # Calculate the sum of all data in the list
print(any((True,1,"Hello"))) # The data in tuples is not False, So it's True
print(all((True,None))) # There is one in the tuple None, Judgment for False

character string

We mentioned earlier that in Python in , String is Python Default data type , It's like double The type is Java The default data type is the same . So for python The characters in String data type , We need to spend a lot of time and energy to study , Now let's explain it as a separate section .
The explanation of string is roughly divided into two parts : Fragment of string and data statistics of string .

Fragment operation of string

Problem introduction :

title="I like Python and I like c++ too"
str_a=title[:7]
print(str_a)
str_b=title[3:9]
print(str_b)
str_c=title[1:5:2]
print(str_c)

In the above program, we can find , In fact, the fragmentation operation of string is very similar to that of sequence . So you can associate memory . stay Python in , Chinese characters and letters are treated as one character , This reduces the occurrence of garbled code in the process of slicing .

Reasons for garbled code in the process of string splitting

We all know , During program compilation , When we operate on characters , It's usually right ASCII Code to operate . According to the tradition ASCII In terms of yards , English characters take up one byte , Chinese takes up two bytes , So if you want to intercept in the string , Consider the number of bytes intercepted , Once the intercepted digits are wrong , There will be chaos .
In project development : There are two commonly used codes :
(1).UTF-8 code , An English character takes up one byte , One Chinese takes up three bytes , Chinese punctuation takes up three bytes , English punctuation takes up one byte .
(2).Unicode code : English characters occupy two bytes , Chinese takes up two bytes , The corresponding punctuation also occupies two bytes .

Simple string operation understanding

Use the previous sequence operation function ( Note that it is not a list operation function ) Implement operations on strings .
for example : Find the largest and smallest characters in the string ;

# coding:UTF-8
title="i like python"
print(" The length of the string is :%d" % (len(title)))
print(" The largest character in the string is :%c" % (max(title)))
print(" The smallest character in the string is :%c" % (min(title)))

When we introduced operators earlier , Explained the member operator , In the string, we can use the member operator to judge whether the data is in the string .

# coding:UTF-8
title="study Python now"
if "Python" in title:
print(" character string “Python” In the string ")
else:
print("no")
String formatting

Through the previous study , We can know , about Python Language , We can choose to format the output , Of course , Formatted output of strings is also possible .
The function of string format output is format() function ,
Function format :
“…{ Member tag ! Transformation format : Format description }…”.format( Parameter class content )
(1). Member tag : Used to define member or parameter sequence number , If not defined , Then the parameters are carried out in sequence .
(2). Transformation format : Perform data format conversion for the data class content of the specified parameters .
(3). Format description : Several configuration options are available .
Conversion marker :

Type character

describe

a

String by Unicode Code output

b

Convert integers to binary numbers

c

Convert an integer to ASCII

d

Decimal integer

e

Convert decimal numbers into scientific notation

E

Convert decimal numbers into scientific and technological expressions ( Capitalization E)

f

Floating point number means , The special value (nan,inf) Convert to lowercase

F

Floating point display , The special value (nan,inf) Convert to uppercase

g

e and f The combination of , If the integer position exceeds 6 Bit use e, Otherwise, use f

G

E and F The combination of , Integer position exceeds 6 Bit use E Express , Otherwise, use F Express

o

Convert integers to octal numbers

s

Output data as string

r

Convert data into information for interpreter output

x

Convert decimal integers to hexadecimal numbers , The letter part is in lowercase

X

Convert decimal to hexadecimal , The letters are capitalized

%

Format the value in bit percentile form

 Format description options

Options

To configure

fill

Blank fill configuration , By default, white space is used to fill the blank part

align

<: Align left ,>: Right alignment ,^: Align center ,=: Place the filled data between the symbol and the data , Only valid for numbers

sign

+: All numbers are signed ,-: Only negative numbers are signed ( Default configuration options ), Space : Positive numbers are preceded by spaces , Negative numbers are preceded by a sign

Digital conversion configuration , Automatically in binary , octal , Hexadecimal and numeric values were added corresponding to the day before yesterday 0b,0o,0x Mark

.

Automatically add... Between every three numbers “,” Separator

width

Define the minimum display width of decimal digits , If not specified , Then determine the width according to the actual class content

precision

Precision bits reserved by data

type

data type

String provided format() The function is more complex , Here are a few cases to learn :

name=" Xiao Ming "
age=18
score=97.5
message=" full name :{}, Age :{}, achievement :{}".format(name,age,score)
print(message)
Running results : full name : Xiao Ming , Age :18, achievement :97.5

The above program is simple to use “{}” To carry on the placeholder , The final output is according to format() Order of function Tags , Line into the final output class .
Of course format() Function when formatting a string , You can also use numerical serial numbers , Or parameters to implement the definition , So as to achieve the automatic matching of parameters and objects .
for example :

name=" Xiao Ming "
age=18
score=97.5
# Use the form of parameters to realize .
print(" full name :{name_a}, Age :{age_a}, achievement :{score_a}".format(name_a=name,age_a=age,score_a=score))
# Use serial number to indicate
print(" full name :{0}, Age :{1}, achievement :{2}".format(name,age,score)) # Pay attention to the serial number and format() The order in the function is related ;
Running results : full name : Xiao Ming , Age :18, achievement :97.5
full name : Xiao Ming , Age :18, achievement :97.5

Through the above procedure, we can know , about format() Use of functions , It can not only facilitate our data output , And reduce the amount of code . however , If you need to define a variable every time to use , Will appear complex ; We know , Lists can store various types of data , Then we can use the index to realize the formatted output of the string :
Code example :

infors=["Coco",18,98.5,180,60]
print(" full name {list_pragram[0]}, Age :{list_pragram[1]}, achievement :{list_pragram[2]}, height :{list_pragram[3]}, weight :{list_pragram[4]}".format(list_pragram=infors))
Running results : full name Coco, Age :18, achievement :98.5, height :180, weight :60

One . Data format processing

Code example :

# coding:UTF-8
print("UNICODE code :{info!a}".format(info=" study hard "))
print(" achievement :{info:6.2f}".format(info=98.5674))
print(" income :{numA:G}, income :{numB:E}".format(numA=92393,numB=92393))
print(" Binary number :{num:#b}".format(num=10))
print(" Octal number :{num:#o}".format(num=10))
print(" Hexadecimal number :{num:#x}".format(num=10))
Running results :
UNICODE code :' study hard '
achievement : 98.57
income :92393, income :9.239300E+04
Binary number :0b1010
Octal number :0o12
Hexadecimal number :0xa
# coding:UTF-8
msg="I like Python,so i will study hard"
print(" The data shows 【{info:^20}】".format(info=msg))
print(" Data filling :{info:_^20}".format(info=msg)) # Custom filler
print(" Filled with signed numbers :{num:^+20.3f}".format(num=12.34578))
print(" Right alignment :{n:>20.2f}".format(n=25)) # Define alignment
print(" Digital usage “,” Separate :{num:,}".format(num=928239329.99765489090))
print(" Set the display accuracy :{info:.9}".format(info=msg))
Running result display :
The data shows 【I like Python,so i will study hard】
Data filling :I like Python,so i will study hard
Filled with signed numbers : +12.346
Right alignment : 25.00
Digital usage “,” Separate :928,239,329.9976549
Set the display accuracy :I like Py

The above program takes us to learn the format operation in string , But for string operation ,Python It also provides related operation functions , In order to reduce the difficulty of programmers .

String manipulation functions

Python There are many types of string handlers in , For example, case conversion , Replace , Split , Connections etc. .
Now let's understand these functions in detail .

function

describe

center()

The string is centered

find(data)

String data lookup , Find the returned index value , No return found -1

join(data)

String connection

split(data【,limit】)

String splitting

lower()

String to lowercase

upper()

String capitalization

capitalize()

title case

replace(old,new【,limit】)

String substitution

translate(mt)

Use the specified replacement rule to replace a single character

maketrans(oc,nc【,d】 )

And translate() Function in combination with , Define the character content to be replaced and delete the character content

strip()

Remove the left and right spaces

Code example :

# coding:UTF-8
# Examples of string manipulation functions
# String display control
info="I like Python,and i want to get good score in Python"
print(info.center(50)) # Data center display , The length is 50
print(info.upper()) # Convert the letters in the string to uppercase
print(info.lower()) # Turn the letters in the string into lowercase
print(info.capitalize()) # The first letter is capitalized
del info
# summary , In the conversion of strings , Do not deal with non alphabetic characters .
# Find the contents of the string
info="New eternity,if i cahnge the word will change"
print(info.find("change")) # Return the position of the query string
#find Function can not only be simply used to find , You can also use the index to find , In order to reduce the search time complexity
print(info.find("word",10,len(info))) # From index to 10 Start looking for , Until the end of the string .
print(info.find("like",20,30)) # The running result is -1, So I didn't find , Although there is like The word , But it's not in the range of the index .
del info
# String connection
url=".".join(["I","like","Python"])
autor="_".join(" Li Hua ")
print(f" full name :{autor}, hobby :{url}")
# String splitting
ip="192.168.1.105"
print(" All data is split into :%s" %(ip.split(".")))
print(" The data part is split into :%s" %(ip.split(".",1))) # Split once
data="2022-7-10 22:51:59"
result=data.split(" ") # here result Equivalent to a list , Separate the date and time with a space
print(" Date split :%s" %(result[0].split("-")))
print(" Time split into :%s" % (result[1].split(":")))
del ip;del data;del result;
# String substitution
info="Hello word!Hello Python!Hello c++"
str_a=info.replace("Hello"," Hello ") # All replacement
str_b=info.replace("Hello"," Hello ",2) # Partial replacement , Replace two times , The system will automatically replace the matching string ;
print(" All replaced strings : %s" % (str_a))
print(" Partially replaced string :%s" % (str_b))
del info
del str_a
del str_b
# Character substitution
str_a="Hello Py th on !H e ll o wo r d!"
# utilize maketrans() Function to create a conversion table
mt_a=str_a.maketrans(" "," "," ") # Delete the blank space ;
print(str_a.translate(mt_a))
str_b="Hello Pyhton! i like you;i hope get you;"
mt_b=str_b.maketrans(" ",".",";")
print(str_b.translate(mt_b))
del str_a; del str_b;
del mt_a; del mt_b;
# Delete the left and right space bars
"""
When we input data , Sometimes there are spaces , If you want to remove the space , Then we can use strip() function ;
"""
login_info=input(" Please enter login information ( Format : name , password )").strip() # Remove the left and right spaces ;
if len(login_info)==0 or login_info.find(",")==-1:
print(" There is a problem with the data entered , Incorrect format , Re input ;")
else:
result=login_info.split(",")
if result[0] and result[1]:
print(" Login successful ")
print(" Congratulations to the user %s Sign in " % (result[0]))
Running results :
I like Python,and i want to get good score in Python
I LIKE PYTHON,AND I WANT TO GET GOOD SCORE IN PYTHON
i like python,and i want to get good score in python
I like python,and i want to get good score in python
39
29
-1
full name : Li _ Hua , hobby :I.like.Python
All data is split into :['192', '168', '1', '105']
The data part is split into :['192', '168.1.105']
Date split :['2022', '7', '10']
Time split into :['22', '51', '59']
All replaced strings : Hello word! Hello Python! Hello c++
Partially replaced string : Hello word! Hello Python!Hello c++
HelloPython!Helloword!
Hello.Pyhton!.i.like.youi.hope.get.you
Login successful
Congratulations to the user lihua Sign in

Dictionaries

Dictionaries (dict) Is a data set of binary even objects ( Or called Hash surface ), All data storage structures are key=value form , Developers just need to pass key You can get the corresponding value The first part gives .

The basic use of dictionaries

The dictionary is made up of several key=value Mapping to a special list structure , It can be used “{ }” Define dictionary data , Considering the convenience of users ,key The value of can be a number , Characters or tuples .

info={"python":"I like you",1024:" This day is programmer's day ",None:" Empty , What also have no "}
print("Python The corresponding value is :%s" % (info["python"]))
print("1024 The corresponding is :%s" % (info[1024]))
print("None The corresponding value is :%s" % (info[None]))


We found out Python The dictionary in is in use , It is very similar to the hash table in the data structure , So it is also very similar to some characteristics in hash table , such as key Values are not allowed to be repeated , because key Once repeated , There will be new class content replacing the old class content .

Code example : Using dictionaries dict() Function definition dictionary

infos=dict([["Python","I like Python"],["student","we should study hard"]]) # List to dictionary ;
member=dict(name=" Li Hua ",age=18,score=97.8)
print(infos)
print(member)


I believe many students will have questions here , Since dictionaries and lists have multiple data storage structures , Why should we implement the structure of dictionary , This is because dictionary structure is generally used for data query , The list is used to realize the output function of data .

Iterative output of dictionary

Dictionaries are essentially It is a list structure formed by several mapping items , In addition to the data query function , It can also be based on for Loop is the iterative output of all data in Xi'an .
Iterative output of dictionary :

infos=dict([["Python","I like Python"],["student","we should study hard"]]) # List to dictionary ;
member=dict(name=" Li Hua ",age=18,score=97.8)
print(infos)
print(member)
for key in infos:
print("%s=%s" % (key,infos[key]))
for key in member:
print("%s=%s" % (key,member[key]))

It can be used directly in the dictionary for Get all the corresponding in the dictionary circularly key Information about , Pass after each iteration key Realization value Data query . Get the dictionary through iteration key Value , Then get the corresponding value, Although this method is simple , however , If a large amount of data is stored , This way will become particularly time-consuming . So it can be used in actual development items() The function of returns directly for each group key and value value .
Code example :

infos=dict([["Python","I like Python"],["student","we should study hard"]]) # List to dictionary ;
member=dict(name=" Li Hua ",age=18,score=97.8)
for key,value in infos.items():
print("%s=%s" % (key,value))
for key,value in member.items():
print("%s=%s" % (key,value))
Dictionary operation function

function

describe

clear()

Empty dictionary data

update(k=v,…)

Update dictionary data

fromkeys(seq[,value])

Create a dictionary , Use the data in the list as key, be-all key Have the same value

get(key[,defaultvalue])

according to key get data

popitem()

Pop up a set of mapping items from the dictionary

keys()

Return to all in the dictionary key data

values()

Returns all in the dictionary value value

# coding:UTF-8
member=dict(name=" Li Hua ",age=18,score=97.5)
member.update(name=" Xiao Ming ",age=20,score=99) # Update of dictionary data
for key,value in member.items():
print("%s:%s" % (key,value))
print(" Use pop Function pops up the specified key:%s, The remaining data is :%s" % (member.pop("name"),member))
del member
member=dict(name=" Li Hua ",age=18,score=97.5)
print(" Use popitem Pop up a set of data values :%s, The remaining data is :%s" % (member.popitem(),member))
#fromkeys() Use of functions ;
dict_a=dict.fromkeys((" Li Hua "," Xiao Ming "),20) # Set a tuple , Values in tuples are treated as key, And the set class content is the same
# Use string to set key, Every character in the string will be treated as a key
dict_b=dict.fromkeys("Hello",100)
print(dict_a)
print(dict_b)
del dict_a
del dict_b
# Use get Function to query data
member=({"name":" Li Xiaoming ","score":90,"age":22})
print("%s" % (member.get("num")))
# Use the functions of sequence to calculate the data
member=dict(chinese=99,english=78,math=100)
print(" Average of all grades %.2f" % (sum(member.values())/(len(member))))

Running results :

summary

(1).Python The sequences in include ; list , Tuples , character string , Dictionaries .
(2). List is a data structure that can be extended by dynamic library , The contents can be accessed according to the index , The class content in a binary is not allowed to be changed .
(3). The operation function in the sequence max(),min(),sum(),len(),all(),any() Function is useful for all sequence structures .
(4). A string is a special sequence , There are several characters , Strings can take advantage of format() Method to implement powerful formatting operations , You can also use library functions to replace strings , Split , Search and so on .
(5). A dictionary is a kind of key=value Set of binary even objects , The main function is based on key Implement correspondence value Data query , It can also be used. update() Function to add, delete, check and modify data , Or use del Keyword deletion specifies key Value .


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