【Update】Python Basic Tutorial: Chapter 6_Data Container

 Original: Public account data talk

【Update】Python Basic Tutorial: Chapter 6_Data Container

Why Study Data Containers

Think about a question: If I want to record 5 students' information, such as names, in the program.

The best way is not to simply define 5 string variables

name1="Wang Lihong"
name2="Zhou Jielun"
name3="Lin Junjie"
name4="Zhang Xueyou"
name5="Liu Dehua"

Although this method can meet our needs, it is a bit cumbersome to write by hand. We only have 5 student information, so if it is 50 or 500, do we really need to define 500 variables? That is definitely unrealistic, so although our writing method can be realized, it is not advanced and inefficient. In order to realize this requirement, we can use the data container to realize it.

This is then done with a variable:

namelist = ["Wang Lihong", "Zhou Jielun", "Lin Junjie", "Zhang Xueyou", "Liu Dehua"]

In this code, a new data structure is defined, which we have never seen before, so this is the data container.

As you can see, this code records 5 pieces of data at one time and saves the 5 pieces of data in a variable. So when we write code, we can easily use one variable to record multiple data, and it can be easily extended even if we need to record more data. This is the most basic value of a data container, which can accommodate multiple copies of data, making our code more elegant and efficient. Therefore, the main purpose of learning data containers is to achieve batch storage and processing of multiple copies of data. This is the greatest value that data containers bring us.

Students who are used to watching videos can watch this free tutorial:

https://www.bilibili.com/video/BV1ZK411Q7uX/?vd_source=704fe2a34559a0ef859c3225a1fb1b42&wxfid=o7omF0RELrnx5_fUSp6D59_9ms3Y

data container

Data Containers in Python

A data type that can hold multiple pieces of data. Each piece of data is called 1 element. Each element can be any type of data, such as strings, numbers, Booleans, etc.

As shown in the picture above, we can see that there is a data container on our side, and inside the container there will be a series of elements such as element 1, element 2, element 6, element 9, and element n.

Then this number can be very, very large. Data containers vary according to their characteristics, such as:

  • Whether to support repeated elements

  • Can it be modified

  • Is it in order, etc.

Divided into 5 categories, namely:

List (list), tuple (tuple), string (str), collection (set), dictionary (dict) We will learn them one by one.

list definition

learning target

  • Master the definition format of the list

why do you need a list

Thinking: How is a person's name (TOM) stored in the program?

Answer: string variable

Thinking: If there are 100 students in a class and everyone's name needs to be stored, how should the program be written? Declare 100 variables?

Answer: No, we can use the list, which can store multiple data at a time

The list (list) type is a type of data container, let's learn it in detail. The basic syntax for defining a list is:

 
 
 
 

# Literal
[element 1, element 2, element 3, element 4,...]

# define variables
variable name = [element 1, element 2, element 3, element 4,...]

# define empty list
variable name = []
variable name = list()

Each data in the list is called an element

  • Marked by []

  • Each element in the list is separated by a comma

how the list is defined

Now let's take a brief look at its case demonstration. Suppose we want to store 3 strings of data, and then print out its content through the print statement, and check its type through the type statement:

 
 
 
 

name_list = ['itheima','itcast','python']
print(name_list)
print(type(name_list))

The output is:

 
 
 
 

['itheima', 'itcast', 'python']
<class 'list'>

At the same time, you can see that his type is called list, so this is what we call a list.

We have defined another list below, then you will find in the list that the three elements seem to be of different types

 
 
 
 

my_list = ['itheima',666,True]
print(my_list)
print(type(my_list))

Then we print out its content after writing, and print out its type at the same time, and we will also find that it can be output normally.

 
 
 
 

['itheima', 666, True]
<class 'list'>

It proves one thing, that is, the element types stored in our list can be different data types.

Since this is the case, let's think about it, the type of elements we store is unlimited, so is it okay for me to store another list in it? It is definitely possible, so if it is said to be stored in the list and then stored in the list. Then this behavior we call it nesting.

 
 
 
 

my_list = [[1,2,3],[4,5,6]]
print(my_list)
print(type(my_list))

We will find that there are two elements in it, the first element is a list, and the second element is also a list. So the code we are currently writing is to write a list with two elements in it, and each element is a list, then we print out the result through the print statement and the type statement:

 
 
 
 

[[1, 2, 3], [4, 5, 6]]
<class 'list'>

It can also be output normally, and the type is also a list type.

Note: The list can store multiple data at a time, and can be of different data types, and supports nesting.

subscript index of the list

learning target

  • Master the subscript index of the list to take out elements from the list

How to get the data at a specific position from the list? We can use: subscript index

As shown in the figure, each element in the list has its position subscript index, from front to back direction, starting from 0, and increasing sequentially. We only need to follow the subscript index to get the element at the corresponding position.

 
 
 
 

name_list =['Tom','Lily','Rose']
print(name_list[0]) # result: Tom
print(name_list[1]) # result: Lily
print(name_list[2]) # result: Rose

List subscript (index) - reverse

Or, you can reverse the index, that is, from the back to the front: starting from -1, decreasing in order (-1, -2, -3...)

As shown in the figure, from the back to the front, the subscript indexes are: -1, -2, -3, decreasing in order.

 
 
 
 

name_list =['Tom','Lily','Rose']
print(name_list[-1]) # result: Rose
print(name_list[-2]) # result: Lily
print(name_list[-3]) # result: tom

subscript (index) of nested list

If the list is a nested list, subscript indexes are also supported. In fact, we need to write two layers of subscript indexes.

As shown in the figure, there are 2 levels of subscripts.

 
 
 
 

# 2-layer nested 1ist
my_list=[[1,2,3],[4,5,6]]

# Get the first 1ist in the inner layer
print(my_list[0]) #Result: [1,2,3]

# Get the first element of the first 1ist in the inner layer
print(my_list[0][0]) #Result: 1

Common operations on lists

learning target

  • Master the common operations (methods) and characteristics of lists

We have learned about the definition of lists and the use of subscript indexes to obtain specified element values. In addition to these two operations, our lists also provide a series of functions: such as inserting elements, deleting elements, and clearing the list. , modifying elements, counting the number of elements, etc., then these functions, we all call it a method called a list.

So here we have a new term called method, so what is method?

Let's recall a content. We have learned about functions before, so we know that a function is an encapsulated code unit that can provide specific functions. In Python, if we define a function in a class and also a member of the class, then the name of this function will no longer be called a function, but will be called a method.

It can be seen that, in fact, functions and methods are actually the same in function, but they are written in different places.

 
 
 
 

# function
def add(x, y)
return x + y

# method
class Student:
def add(self,x , y):
return x + y

Regarding the definition of classes and methods, we learned in the object-oriented chapter, so far we only know how to use methods.

List query function (method)

A function is an encapsulated unit of code that provides a specific functionality. In Python, if a function is defined as a member of a class (class), then the function will be called: the method method is the same as the function function, with incoming parameters and a return value, but the format of the method is different: the use of the function:

 
 
 
 

num = add(1,2)

Method usage:

 
 
 
 

student = Student()
num = student.add(1,2)

  • Find the subscript of an element

Function: Find the subscript of the specified element in the list, if not found, report ValueError  

Syntax: list.index(element)

index is the built-in method (function) of the list object (variable)

 
 
 
 

my_list = ['itheima','itcast','python']
print(my_list.index('itcast')) # 结果1

list modification function (method)

  • Modify the element value at a specific position (index):

  • Syntax: list[subscript] = value

You can use the syntax above to directly reassign (modify) the value of the specified subscript (both forward and reverse subscripts are acceptable)

 
 
 
 

#Forward subscript
my_list = [1,2,3]
my_list[0] = 5
print(my_list) #Result: [5,2,3]

#Reverse subscript
my_list = [1,2,3]
my_list[ -3] = 5

print(my_list) # result: [5,2,3]

  • Insert element:

Syntax: list.insert(subscript, element), insert the specified element at the specified subscript position

 
 
 
 

my_list = [1,2,3]
my_list.insert(1,"itheima")
print(my_list) # 结果 [1, 'itheima', 2, 3]

  • Append element:

Syntax: list.append(element), append the specified element to the end of the list

 
 
 
 

my_list = [1,2,3]
my_list.append(4)
print(my_list) # 结果 [1, 2, 3, 4]

my_list = [1,2,3]
my_list.append([4,5,6])
print(my_list) #结果 [1, 2, 3, [4, 5, 6]]

  • Append element method 2:

Syntax: list.extend(other data containers), take out the contents of other data containers, and append them to the end of the list in turn

 
 
 
 

my_list = [1,2,3]
my_list.extend([4,5,6])
print(my_list) # 结果 [1, 2, 3, 4, 5, 6]

  • Remove element:

Syntax 1: del list[subscript]  

Syntax 2: list.pop(subscript)

 
 
 
 

my_list = [1,2,3]
#method 1
del my_list[0]
print(my_list) #result[2, 3]
#method 2
my_list.pop(0)
print(my_list) #result[2, 3]

  • removes the first occurrence of an element in the list

Syntax: list.remove(element)

 
 
 
 

my_list = [1,2,3,2,3]
my_list.remove(2)
print(my_list) # 结果:[1, 3, 2, 3]

  • clear list content

Syntax: list.clear()

 
 
 
 

my_list = [1,2,3]
my_list.clear()
print(my_list) # 结果[]

  • Count the number of elements in a list

Syntax: list.count(element)

 
 
 
 

my_list = [1,1,1,2,3]
print(my_list.count(1)) # result: 3

List query function (method)

  • Count how many elements are in the list Syntax: len(list)

An int number can be obtained, indicating the number of elements in the list

 
 
 
 

my_list = [1,2,3,4,5]
print(len(my_list)) # result: 5

List Methods - Overview

serial number

How to use

effect

1

list.append(element)

Append an element to the list

2

list.extend(container)

Take out the contents of the data container in turn and append them to the end of the list

3

list.insert(subscript, element)

Insert the specified element at the specified subscript

4

del list[subscript]

Delete the specified subscript element of the list

5

list.pop(subscript)

Delete the specified subscript element of the list

6

list.remove(element)

From front to back, remove the first occurrence of this element

7

list.clear()

clear the list

8

list.count(elements)

counts the number of times this element occurs in the list

9

list.index(element)

Find the specified element in the subscript of the list and cannot find an error ValueError

10

len(list)

counts how many elements are in the container

List Method - Description

There are so many functional methods, students don’t need to memorize them.

Learning programming is not only the Python language itself, but you will learn more framework technologies according to the direction in the future.

Except for the frequently used ones, most of them cannot be remembered.

What we have to do is to have a vague impression and know that there is such a usage.

You can check the information at any time when you need it.

Features of the list

After studying the list above, it can be concluded that the list has the following characteristics:

  • Can hold multiple elements (upper limit is 2**63-1, 9223372036854775807)

  • Can accommodate different types of elements (mixed)

  • Data is stored in order (with subscript serial number)

  • Duplicate data is allowed

  • Can be modified (add or remove elements, etc.)

Practice case: common function exercises

There is a list, the content is: [21, 25, 21, 23, 22, 20], which records the age of a group of students

Please pass the function (method) of the list, to it

  1. Define this list and receive it with variable

  2. Appends a number 31, to the end of the list

  3. Append a new list [29, 33, 30] to the end of the list

  4. Take out the first element (should be: 21)

  5. Take out the last element (should be: 30)

  6. Find element 31, subscript position in the list

Reference Code:

 
 
 
 

"""
Exercise to demonstrate the common operation of List
"""

# 1. Define this list and use variables to receive it, the content is: [21, 25, 21, 23, 22, 20]
mylist = [21, 25, 21 , 23, 22, 20]

# 2. Append a number 31 to the end of the list
mylist.append(31)

# 3. Append a new list [29, 33, 30] to the end of the list
mylist.extend([29 , 33, 30])
# 4. Take out the first element (should be: 21)
num1 = mylist[0]
print(f"Take out the first element from the list, it should be 21, actually: {num1 }")

# 5. Take out the last element (should be: 30)
num2 = mylist[-1]
print(f"Take out the last element from the list, it should be 30, actually: {num2}")

# 6. Find element 31, the subscript position in the list
index = mylist.index(31)
print(f"The subscript position of element 31 in the list is: {index}")
print(f"The content of the final list is: {mylist}")

Output result:

 
 
 
 

Take out the first element from the list, it should be 21, it is actually: 21
Take the last element out of the list, it should be 30, it is actually: 30
The subscript position of element 31 in the list is: 6
The last list The content of is: [21, 25, 21, 23, 22, 20, 31, 29, 33, 30]

List (list) traversal

learning target

  • Master the use of while loop to traverse the elements of the list  

  • Master the use of for loop to traverse the elements of the list

List traversal - while loop

Since the data container can store multiple elements, there will be a need to sequentially take out elements from the container for operation. The behavior of taking out the elements in the container for processing in turn is called: traversal and iteration. How to iterate through the elements of the list? You can use the while loop you learned earlier

  • How to extract the elements of the list in the loop?

  • Use list [subscript] to get out

How are the loop conditions controlled?

  • Define a variable to represent the subscript, starting from 0

  • The loop condition is the subscript value < the number of elements in the list

 
 
 
 

index = 0
while index < len(list):
element = list[index]
to process the element
index += 1

List traversal - for loop

In addition to the while loop, there is another form of loop in Python: the for loop.

Compared with while, the for loop is more suitable for traversing data containers such as lists.

grammar:

 
 
 
 

# for temporary variable in data container:
# process the temporary variable

Example demonstration:

 
 
 
 

my_list = [1,2,3,4,5,]
for i in my_list:
print(i)

#The result is:
1
2
3
4
5

Indicates that, from the container, elements are sequentially taken out and assigned to temporary variables.

As a result, in each loop, we can process temporary variables (elements).

Each cycle takes out the elements in the list and assigns them to the variable i for operation

Comparison of while loop and for loop

The while loop and the for loop are both loop statements, but the details are different:

  • On loop control:

  • The while loop can customize the loop condition and control it by itself

  • The for loop cannot customize the loop condition, it can only take out data from the container one by one

  • On an infinite loop:

  • The while loop can be infinitely looped through conditional control

  • The for loop is theoretically impossible, because the capacity of the traversed container is not infinite

  • In usage scenarios:

  • The while loop is suitable for any scenario where you want to loop

  • The for loop is suitable for scenarios that traverse data containers or simple fixed-number loop scenarios

the code

 
 
 
 

my_list = [1,2,3,4,5]
for i in my_list:
print("Xiaomei, I like you")

The output is:

 
 
 
 

Mei, I like you
Mei, I like you
Mei, I
like you
Mei, I like you

Practice case: take out the even number in the list

Define a list, the content is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  • Traverse the list, take out the even numbers in the list, and store them in a new list object

  • Use while loop and for loop to operate once

 
 
 
 

Through the while loop, take out even numbers from the list: [1,2,3,4,5,6,7,8,9,10] to form a new list: [2,4,6,8,10]
loop through f0 , take even numbers from the list: [1,2,3,4,5,6,7,8,9,10] to form a new list: [2,4,6,8,10]

hint:

  • Confirm even number by if judgment

  • Add elements through the append method of the list

Reference Code:

 
 
 
 

# while 方法
old_list = [1,2,3,4,5,6,7,8,9,10]
new_list = []
i = 0
while i < len(old_list):
if old_list[i] % 2 == 0:
new_list.append(old_list[i])
i += 1
print(new_list)

# for 方法
old_list = [1,2,3,4,5,6,7,8,9,10]
new_list = []
for num in old_list:
if num % 2 == 0:
new_list.append(num)
print(new_list)

Definition of tuple

learning target  

  • Master the definition format of tuples

Why do you need tuples

Ok, first let's think about a question: why do we need tuples? The list we learned before is very powerful, it can store multiple element types and is not limited, but let's think about it: the list has a characteristic, it is modifiable. If the information I need to pass cannot be tampered with, lists are not a good fit. Therefore, we need to introduce another data container - tuple.

Tuples, like lists, can store multiple elements of different types, but their biggest difference is that once a tuple is defined, it cannot be modified, so it can be regarded as a read-only list. Therefore, if we need to encapsulate data in the program, but do not want the encapsulated data to be tampered with, then tuples are very suitable.

Next let's look at how to define tuples.

definition tuple

Tuple definition: use parentheses to define a tuple, and use commas to separate each data. The data can be of different data types.

 
 
 
 

# Define tuple literal
(element, element, element, ..., element,)
# Define tuple variable
variable name = (element, element, element, ..., element,)

# Define empty tuple
variable name = () # Mode 1
variable name = tuple() # Mode 2

Precautions:

 
 
 
 

# Define a tuple of 3 elements
t1 = (1,"Hello",True)

# Define a tuple of 1 element
t2 = ("Hello",) #Note that a comma must be included, otherwise it is not a tuple

Note: The tuple has only one data, and a comma should be added after this data

Tuples also support nesting:

 
 
 
 

# Define a nested tuple
t1=((1,2,3),(4,5,6))
print(t1[0][0]) #Result: 1

Related operations on tuples:

 
 
 
 

#Get the data according to the subscript (index)
t1=(1,2,'he11o')
print(t1[2]) #Result: 'he11o'

#According to index(), find the first matching item of a specific element

t1= (1,2,'hello',3,4,'hello')

print(t1.index('hello')) # Result: 2

# Count the number of times a certain data appears in the tuple
t1=(1,2 ,'he11o',3,4,'he11o')

print(t1.count('he1lo')) # Result: 2


# Count the number of elements in the tuple
t1=(1,2,3)
print(len( t1)) # result 3

serial number

method

effect

1

index()

Find a certain data, if the data exists, return the corresponding subscript, otherwise report an error

2

count()

Count the number of times a data appears in the current tuple

3

len(tuple)

Count the number of elements in a tuple

Due to the unmodifiable nature of tuples, there are very few operation methods

Related operations on tuples - Notes

  • The content of the tuple cannot be modified, otherwise an error will be reported directly

 
 
 
 

# Try to modify the tuple content
t1=(1,2,3)
t1[0]=5
TypeError: 'tuple' object does not support item assignment

  • You can modify the contents of the list in the tuple (modify elements, add, delete, reverse, etc.)

 
 
 
 

# Try to modify the tuple content
t1 = (1,2,['itheima','itcast'])
t1[2][1]='best'

print(t1) #Result: (1,2,['itheima' ,'best'])
(1, 2, ['iheima', 'best'])

  • Cannot replace list with other lists or other types

 
 
 
 

# Try to modify the tuple content
t1 = (1,2,['itheima','itcast'])
t1[2]= [1,2,3]
print(t1)
TypeError: 'tuple' object does not support item assignment

Traversal of tuples

Like lists, tuples can also be iterated.

It can be traversed using while loop and for loop

while loop

 
 
 
 

my_tuple=(1,2,3,4,5)
index =0
while index < len(my_tuple):
print(my_tuple[index])
index += 1

for loop

 
 
 
 

my_tuple=(1,2,3,4,5)
for i in my_tuple:
print(i)

operation result

 
 
 
 

1
2
3
4
5

Features of tuples

After the above study of tuples, it can be concluded that the list has the following characteristics:

  • Can hold multiple data

  • Can accommodate different types of data (mixed)

  • Data is stored in order (subscript index)

  • Duplicate data is allowed

  • Cannot be modified (adding or deleting elements, etc.)

  • Support for loop

Most of the features are the same as list, the difference lies in the unmodifiable features.

Practice case: basic operations on tuples

Define a tuple, the content is: ('Jay Chow', 11, ['football', 'music']), the record is a student's information (name, age, hobbies) Please pass the function of the tuple (method ), which is

  1. Query the subscript position where the age is located

  2. Look up a student's name

  3. Delete football from student hobbies

  4. Add hobbies: coding to the hobbies list

  5. Query the subscript position of its age:

Reference Code

 
 
 
 

# Query the subscript position of their age
student = ('Jielun Zhou', 11, ['football', 'music'])
age_index = student.index(11)
print(age_index) # Output: 1

# Query the student's Name:
student = ('Jay Chou', 11, ['football', 'music'])
name = student[0]
print(name) # output: Jay Chou

# or
student = ('Jay Chou', 11, ['football', 'music'])
name = student.index('Jay Chou')
print(name) # Output: 0

# Delete football in the student's hobby:
student = ('Jay Chou', 11 , ['football', 'music'])
student[2].remove('football')
print(student) # Output: ('Jay Chow', 11, ['music'])

# Add hobbies: coding to In the hobby list:
student = ('Jay Chou', 11, ['football', 'music'])
student[2].append('coding')
print(student) # Output: ('Jay Chow', 11, ['football', 'music', 'coding'])

string

learning target

  • Master common operations on strings

Recognize the string

In this section let's learn about an old friend - strings. The learning goal of this section is also very simple. We need to learn about strings from the perspective of data containers and master its common operations.

Although strings do not seem to store a lot of data as obviously as lists or tuples, it is undeniable that strings are also a type of data container, which is a container of characters. A string can hold any number of characters.

For example, the string "iheima", if it is regarded as a data container, it will look like the picture below, where each character is an element, and each element also has a subscript index.

subscript (index) of the string

Like other containers such as lists and tuples, strings can also be accessed through subscripts

  • From front to back, subscripts start from 0

  • From back to front, subscripts start from -1

 
 
 
 

#Get specific position characters through subscript
name ="itheima"
print(name[0]) #result i
print(name[-1]) #result a

Like tuples, strings are one: unmodifiable data containers. so:

  • Modify the character of the specified subscript (eg: string[0] = "a")

  • Remove the character of a specific subscript (such as: del string[0], string.remove(), string.pop(), etc.)

  • Append characters, etc. (eg: String.append())

Neither could be completed. If you have to do it, you can only get a new string, and the old string cannot be modified.

Common operations on strings

  • Find the subscript index value of a specific string

Syntax: string.index(string)

 
 
 
 

my_str = "itcast and itheima"
print(my_str.index("and")) # 结果7

  • string replacement

Syntax: string.replace(string1, string2)

Function: replace all in the string: string 1 with string 2

Note: instead of modifying the string itself, a new string is obtained

 
 
 
 

name = "itheima itcast"
new_name=name.replace("it","Chuanzhi")
print(new_name) # Result: Chuanzhi heima Chuanzhi cast

print(name) # Result: itheima itcast

As you can see, the string name itself does not change but gets a new string object

  • string splitting

Syntax: string.split(delimiter string)

Function: According to the specified delimiter string, divide the string into multiple strings and store them in the list object

Note: The string itself is unchanged, but a list object is obtained

 
 
 
 

name="Chuanzhi Podcast Chuanzhi Education Dark Horse Programmer Erudite Valley"
name_list = name.split(" ")

print(name_list) # Result: [Chuanzhi Podcast, 'Chuanzhi Education, Dark Horse Programmer, Erudite Valley
print(type (name_list)) # Result: <class!1ist'>

It can be seen that the string is split according to the given <space>, turned into multiple substrings, and stored in a list object.

  • Regular operation of strings (remove leading and trailing spaces)

Syntax: String.strip()

 
 
 
 

my_str = "itheima and itcast"
print(my_str.strip()) # 结果:"itheima and itcast"

  • Regular operation of strings (go and specify strings before and after)

Syntax: string.strip(string)

 
 
 
 

my_str ="12itheima and itcast21"
print(my_str.strip("12")) # 结果:"itheima and itcast"

Note that the "12" passed in is actually: "1" and "2" will be removed according to a single character.

  • Count the number of occurrences of a string in a string

Syntax: string.count(string)

 
 
 
 

my_str = "itheima and itcast"
print(my_str.count ("it")) # 结果:2

  • Count the length of the string

Syntax: len(string)

 
 
 
 

my_str="1234abcd!@#$Dark Horse Programmer"
print(len(my_str)) #Result: 20

As can be seen:

  • numbers (1, 2, 3...)

  • Letters (abcd, ABCD, etc.)

  • Symbols (space, !, @, #, $, etc.)

  • Chinese

Both count as 1 character so the above code results in 20

Summary of common string operations

serial number

operate

illustrate

1

string[subscript]

Extract the character at a specific position according to the subscript index

2

string.index(string)

Find the subscript of the first occurrence of the given character

3

string.replace(string1, string2)

Replacing all string 1 in the string with string 2 will not modify the original string, but get a new one

4

string.split(string)

According to the given string, delimiting the string will not modify the original string, but get a new list

5

string.strip() string.strip(string)

Remove leading and trailing spaces and newlines or specify a string

6

string.count(string)

Count the number of occurrences of a string in a string

7

len(string)

Count the number of characters in a string

String Traversal

Like lists and tuples, strings also support while loops and for loops for traversal

while loop

 
 
 
 

my_str = "Dark Horse Programmer"
index = 0
while index < len(my_str):
print(my_str[index])
index += 1

for loop

 
 
 
 

my_str = "Dark Horse Programmer"
for i in my_str:
print(i)

The output results are:

 
 
 
 

Dark
Horse
Programmer
_
_

Characteristics of strings

As a data container, strings have the following characteristics:

  • Only strings can be stored

  • Any length (depends on memory size)

  • Support subscript index

  • Allow duplicate strings to exist

  • Cannot be modified (adding or deleting elements, etc.)

  • Support for loop

Basically the same as lists and tuples

The difference from lists and tuples is that the type that a string container can hold is a single type, which can only be a string type.

Unlike lists, the same as tuples: strings cannot be modified

Exercise example: splitting a string

Given a string: "itheima itcast boxuegu"

  • Count how many "it" characters are in the string

  • Replace all spaces in the string with characters: "|"

  • And split the string according to "|" to get a list

hint:

 
 
 
 

The string itheima itcast boxuegu contains: 2 it characters
The string itheima itcast boxuegu, after being replaced with spaces, the result: itheima|itcastboxuegu
The string itheima|itcastlboxuegu, separated by |, get: ['itheima','itcast', 'boxuegu']

count、replace、split

Sample code:

 
 
 
 

"""
Exercise demonstration of string after class
"itheima itcast boxuegu"
"""
my_str = "itheima itcast boxuegu"
# Count how many "it" characters are in the string
num = my_str.count("it")
print(f" There are {num} it characters in the string {my_str}")
# Replace all spaces in the string with characters: "|"
new_my_str = my_str.replace(" ", "|")
print(f"string After {my_str} is replaced with spaces, the result is: {new_my_str}")
# and split the string according to "|" to get the list
my_str_list = new_my_str.split("|")
print(f"string {new_my_str} according to | The result after splitting is: {my_str_list}")

Slicing of data containers (sequences)

learning target

  • understand what is a sequence

  • Master the slice operation of the sequence

sequence

So, what is a sequence? Sequence refers to a type of data container whose content is continuous and orderly, and which can be indexed by subscripts. The lists, tuples, and strings we learned before all satisfy these characteristics, so they can all be called sequences. As shown in the figure below, they are all typical sequences: elements are closely arranged one by one, adjacent elements are continuous, and subscript indexing operations are supported.

The concept of sequence is relatively simple. Now let's look at the operation of sequence. One of the commonly used operations is slicing.

Common operations on sequences - slicing

Sequences support slicing, namely: lists, tuples, and strings, all of which support slicing operations

Slicing: Take a subsequence from a sequence

Syntax: sequence [start subscript: end subscript: step size]

Indicates that from the sequence, starting from the specified position, taking out elements in sequence, and ending at the specified position, a new sequence is obtained:

  • The start subscript indicates where to start, it can be left blank, and it will be regarded as starting from the beginning

  • The end subscript (not included) indicates where to end, it can be left blank, it will be regarded as intercepted to the end

  • The step size indicates that the interval of elements is taken in turn

  • Step size 1 means, take elements one by one

  • A step size of 2 means that one element is skipped each time

  • The step size N means that N-1 elements are skipped each time to take

  • If the step size is a negative number, it is reversed (note that the start subscript and the end subscript should also be marked in reverse)

Note that this operation does not affect the sequence itself, but instead results in a new sequence (list, tuple, string)

Slicing Demo of a Sequence

 
 
 
 

my_list = [1, 2, 3, 4, 5]
new_list = my_list[1:4] # Start with subscript 1, end with subscript 4 (excluding), step 1
print(new_list) # Result: [2, 3 , 4]

my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:] # start from the beginning, end at the end, step size 1
print(new_tuple) # result: (1, 2, 3, 4, 5 )

my_list = [1, 2, 3, 4, 5]
new_list = my_list[::2] # start from the beginning, end at the end, step size 2
print(new_list) # result: [1, 3, 5]

my_str = " 12345"
new_str = my_str[:4:2] # Start from the beginning, end at subscript 4 (not included), step size 2
print(new_str) # Result: "13"

my_str = "12345"
new_str = my_str[::- 1] # Start from the beginning (last), end to the end, step size -1 (reverse order)
print(new_str) # Result: "54321"

my_list = [1, 2, 3, 4, 5]
new_list = my_list[3:1 :-1] # Start from subscript 3 and end at subscript 1 (excluding), step size -1 (reverse order)
print(new_list) # Result: [4, 3]

my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:1:-2]
# Start from the beginning (last), end at subscript 1 (excluding), step -2 (reverse order)
print(new_tuple ) # result: (5, 3)

As you can see, this operation is common to lists, tuples, and strings

At the same time, it is very flexible. According to the needs, the starting position, the ending position, and the step size (forward and reverse order) can be controlled by yourself.

Practice case: sequence slice practice

There is a string: "Thousands of salary months, the programmers are here, nohtyP learns"

  • Please use any method you have learned to get "Dark Horse Programmer"

Available methods for reference:

  • Reverse string, slice out or slice out, then reverse

  • split "," replace "to" is empty, reverse string

 
 
 
 

"""
Exercise after class of slicing of the demo sequence
"If the salary month is over, the programmer will learn from nohtyP" ""
"
my_str = "After the salary month, the programmer will come from nohtyP"
# Reverse order String, slice out
result1 = my_str[::-1][9:14]
print(f"Method 1 result: {result1}")
# slice out, then reverse order
result2 = my_str[5:10][::- 1]
print(f"Method 2 result: {result2}")

# split separated", "replace "to" is empty, reverse string
result3 = my_str.split(",")[1].replace("to ", "")[::-1]
print(f"Method 3 result: {result3}")

Data container: set (collection)

learning target

  • Master the definition format of collections

  • Master the characteristics of collections

  • Master common operations on collections

Why use collections

We have come into contact with the three data containers of lists, tuples, and strings. Basically meet most usage scenarios.

Why do you need to learn a new collection type?

Analyze by characteristics:

  • Lists are modifiable, support repeating elements, and are ordered

  • Tuples and strings are not modifiable, support repeated elements and are in order Students, do you see some limitations?

The limitation is this: they all support repeating elements. If the scene needs to deduplicate the content, lists, tuples, and strings are inconvenient. The main feature of the collection is that it does not support the repetition of elements (with its own deduplication function), and the content is out of order

collection definition

Basic syntax:

 
 
 
 

#Define collection literal
{element, element,...., element}

#Define collection variable
variable name={element, element,...,element}

#define empty collection
variable name=set()

Basically the same definition as lists, tuples, strings, etc.: 

  • List use: []

  • Tuple use: ()

  • String use: ""

  • Collection usage: {}

sample code

 
 
 
 

names = {"Dark Horse Programmer","Chuanzhi Podcast","itcast","itheima","Dark Horse Programmer","Chuanzhi Podcast"} print(names
)

operation result

 
 
 
 

{'itcast', 'Chuanzhi Podcast', 'Dark Horse Programmer', 'itheima'}

It can be seen from the results: deduplication and disorder because the elements need to be removed, so the order cannot be guaranteed to be consistent with the reprocessing at the time of creation

Common operations on collections - modify

First of all, because the collection is unordered, the collection does not support subscript index access, but the collection, like the list, allows modification, so let's take a look at the modification method of the collection.

  • add new element

Syntax: collection.add(element).

Function: Add the specified element to the collection

Result: the collection itself is modified, new elements are added

 
 
 
 

my_set = {"Hello","World"}
my_set.add("itheima")
print(my_set) # 结果 {'Hello','itheima','World']

  • remove element

Syntax: collection.remove(element)

Function: remove the specified element from the collection

Result: the collection itself is modified, removing the element

 
 
 
 

my_set = {"Hello","World","itheima"}
my_set.remove("Hello")
print(my_set) # 结果{'World','itheima'

  • Randomly remove elements from a collection

Syntax: collection.pop()

Function to randomly take an element from a collection

Result: A result of one element will be obtained. At the same time the collection itself is modified and elements are removed

 
 
 
 

my_set = {"Hello","World","itheima"}
element =my_set.pop()
print(my_set) #result {'World','iheima'}
print(element) #result'He11o

  • empty collection

Syntax: collection.clear()

function, emptying the collection

Result: the collection itself is emptied

 
 
 
 

my_set = {"Hello","World","itheima"}
my_set.clear()
print(my_set) #Result: set() empty set

  • Take the difference of 2 sets

Syntax: set1.difference(set2),

Function: Take out the difference between set 1 and set 2 (set 1 has but set 2 does not)

Result: get a new set, set 1 and set 2 unchanged

 
 
 
 

set1 = {1,2,3}
set2 = {1,5,6}
set3 = set1.difference(set2)
print(set3) # result: {2,3} the new set
print(set1) # result: { 1,2,3} unchanged
print(set2) # Result: {1,5,6} unchanged

  • Eliminate the difference of 2 sets

Syntax: set1.difference_update(set2)

Function: Compare set 1 and set 2, delete the same elements as set 2 in set 1.

Result: set 1 is modified, set 2 is unchanged

 
 
 
 

setl ={1,2,3}
set2={1,5,6}
set1.difference_update(set2)
print(set1) # result: {2,3]
print(set2) # result: {1,5,6}

  • 2 collections merged

Syntax: set1.union(set2)

Function: Combine set 1 and set 2 into a new set

Result: get a new set, set 1 and set 2 unchanged

 
 
 
 

set1 = {1,2,3}
set2 = {1,5,6}
set3 = set1.union(set2)
print(set3) # result: {1,2,3,5,6}, new set
print(set1 ) # Result: {1,2,3}, set1 unchanged
print(set2) # Result: {1,5,6}, set2 unchanged

Common operations on collections - collection length

  • View the number of elements in a collection

Syntax: len(collection)

Function: count how many elements are in the collection

Result: get an integer result

 
 
 
 

set1={1,2,3}
print(len(set1)) # result 3

Common operations on collections - for loop traversal

Collections also support for loop traversal

 
 
 
 

set1={1,2,3}
for i in set1:
print(i)

# 结果
1
2
3

Note: collections do not support subscript indexes, so the use of while loops is not supported.

Collection of common functions summary

serial number

operate

illustrate

1

collection.add(element)

add an element to the set

2

collection.remove(element)

removes the specified element from the collection

3

collection.pop()

Randomly select an element from a collection

4

Set.clear()

empty the collection

5

set1.difference(set2)

Get a new set, which contains the difference set of 2 sets, and the contents of the original 2 sets remain unchanged

6

set1.difference_update(set2)

In set 1, delete elements present in set 2 set 1 is modified, set 2 is unchanged

7

Collection 1.union(collection 2)

Get a new collection, containing all the elements of the two collections, the contents of the original two collections remain unchanged

8

len(collection)

Get an integer that records the number of elements in the collection

Collection Features

After the above study of collections, it can be concluded that collections have the following characteristics:

  • Can accommodate multiple data • Can accommodate different types of data (mixed)

  • Data is stored out of order (subscript indexes are not supported)

  • Duplicate data is not allowed

  • Can be modified (add or remove elements, etc.)

  • Support for loop

Practice case: information deduplication

There are the following list objects: my_list = ['Dark Horse Programmer', 'Chuanzhi Podcast', 'Dark Horse Programmer', 'Chuanzhi Podcast', 'itheima', 'itcast', 'itheima', 'itcast', 'best '] please:

  • define an empty collection

  • Iterating through the list with a for loop

  • Adding elements of a list to a collection in a for loop

  • Finally get the collection object after deduplication of elements, and print out

Sample code:

 
 
 
 

"""
演示集合的课后练习题
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客',
'itheima', 'itcast', 'itheima', 'itcast', 'best']
"""
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客',
'itheima', 'itcast', 'itheima', 'itcast', 'best']

# 定义一个空集合
my_set = set()

# 通过for循环遍历列表
for element in my_list:
# 在for循环中将列表的元素添加至集合
my_set.add(element)

# 最终得到元素去重后的集合对象,并打印输出
print(f"列表的内容是:{my_list}")
print(f"通过for循环后,得到的集合对象是:{my_set}")

字典的定义

学习目标

  • 掌握字典的定义格式

为什么使用字典

生活中的字

通过【字】就能找到对应的【含义】

所以,我们可以认为,生活中的字典就是记录的一堆:【字】:【含义】 【字】:【含义】 ..

为什么需要字典

Python中字典和生活中字典十分相像:

生活中的字典

Python中的字典

【字】:【含义】【字】:【含义】

可以按【字】找出对应的【含义】

Key: Value Key: Value

可以按【Key】找出对应的【Value】

老师有一份名单,记录了学生的姓名和考试总成绩。

姓名

成绩

王力鸿

77

周杰轮

88

林俊节

99

现在需要将其通过Python录入至程序中,并可以通过学生姓名检索学生的成绩。使用字典最为合适:

 
 
 
 

{"王力鸿":99,
"周杰轮":88,
"林俊节":77
}

可以通过Key(学生姓名),取到对应的Value(考试成绩)

所以,为什么使用字典?

因为可以使用字典,实现用key取出Value的操作

字典的定义

字典的定义,同样使用{},不过存储的元素是一个个的:键值对,如下语法:

 
 
 
 

#定义字典字面量
{key:value,key:value,......,key:value}
#定义字典变量
my_dict = {key:value,key:value,......,key:value}
#定义空字典
my_dict ={} # 空字典定义方式1
my_dict= dict{} # 空字典定义方式2

  • 使用{}存储原始,每一个元素是一个键值对

  • 每一个键值对包含Key和Value(用冒号分隔)

  • 键值对之间使用逗号分隔

  • Key和Value可以是任意类型的数据(key不可为字典)

  • Key不可重复,重复会对原有数据覆盖

前文中记录学生成绩的需求,可以如下记录:

 
 
 
 

stu_score = {"王力鸿":99,"周杰轮":88,"林俊节":77}

字典数据的获取

字典同集合一样,不可以使用下标索引

但是字典可以通过Key值来取得对应的Value

 
 
 
 

# 语法,字典[Key]可以取到对应的Value
stu_score={"王力鸿":99,"周杰轮":88,"林俊节":77}
print(stu_score["王力鸿"]) # 结果99
print(stu_score["周杰轮"]) # 结果88
print(stu_score["林俊节"]) # 结果77

字典的嵌套

字典的Key和Value可以是任意数据类型(Key不可为字典)那么,就表明,字典是可以嵌套的需求如下:记录学生各科的考试信息

姓名

语文

数学

英语

王力鸿

77

66

33

周杰轮

88

86

55

林俊节

99

96

66

代码:

 
 
 
 

stu_score={"王力鸿":{"语文":77,"数学":66,"英语":33},"周杰轮":{"语文":88,"数学":86,"英语":55},
"林俊节":{"语文":99,"数学":96,"英语":66}}

优化一下可读性,可以写成:

 
 
 
 

stu_score = {
"王力鸿":{"语文":77,"数学":66,"英语":33},
"周杰轮":{"语文":88,"数学":86,"英语":55},
"林俊节":{"语文":99,"数学":96,"英语":66}
}

嵌套字典的内容获取,如下所示:

 
 
 
 

stu_score = {
"王力鸿":{"语文":77,"数学":66,"英语":33},
"周杰轮":{"语文":88,"数学":86,"英语":55},
"林俊节":{"语文":99,"数学":96,"英语":66}
}
print(stu_score["王力鸿"]) # 结果:{"语文":77,"数学":66,"英语":33}
print(stu_score["王力鸿"]["语文"]) # 结果:77
print(stu_score["周杰轮"]["数学"]) # 结果:86

字典的常用操作

学习目标

  • 掌握字典的常用操作

  • 掌握字典的特点

字典的常用操作

  • 新增元素

语法:字典[Key] = Value

结果:字典被修改,新增了元素

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}

# 新增:张学油的考试成绩
stu_score['张学油']=66
print(stu_score) # 结果:{王力鸿:77,'周杰轮:88,林俊节:99,张学油:66}

  • 更新元素

语法:字典[Key] = Value

结果:字典被修改,元素被更新

注意:字典Key不可以重复,所以对已存在的Key执行上述操作,就是更新Value值

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
# 更新:王力鸿的考试成绩
stu_score['王力鸿']=100
print(stu_score) # 结果:{王力鸿:100,周杰轮:88,林俊节:99}

  • 删除元素

语法:字典.pop(Key)

结果:获得指定Key的Value,同时字典被修改,指定Key的数据被删除

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
value=stu_score.pop("王力鸿")
print(value) # 结果:77
print(stu_score) # 结果:{"周杰轮":88,"林俊节":99}

  • 清空字典

语法:字典.clear()

结果:字典被修改,元素被清空

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
stu_score.clear()
print(stu_score) # 结果:{}

  • 获取全部的key

语法:字典.keys()

结果:得到字典中的全部Key

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
keys = stu_score.keys()
print(keys) # 结果:dict_keys(['王力鸿','周杰轮','林俊节])

  • 遍历字典

语法:for key in 字典.keys()

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
keys = stu_score.keys()
for key in keys:
print(f"学生:{key},分数:{stu_score[key]}")
学生:王力鸿,分数:77
学生:周杰轮,分数:88
学生:林俊节,分数:99

注意:字典不支持下标索引,所以同样不可以用while循环遍历。

  • 计算字典内的全部元素(键值对)数量

语法:len(字典)

结果:得到一个整数,表示字典内元素(键值对)的数量

 
 
 
 

stu_score ={
"王力鸿":77,
"周杰轮":88,
"林俊节":99
}
print(len(stu_score)) # 结果 3

字典的常用操作总结

编号

操作

说明

1

字典[Key]

获取指定Key对应的Value值

2

字典[Key] = Value

添加或更新键值对

3

字典.pop(Key)

取出Key对应的Value并在字典内删除此Key的键值对

4

字典.clear()

清空字典

5

字典.keys()

获取字典的全部Key,可用于for循环遍历字典

6

len(字典)

计算字典内的元素数量

字典的特点

经过上述对字典的学习,可以总结出字典有如下特点:

  • 可以容纳多个数据 • 可以容纳不同类型的数据

  • 每一份数据是KeyValue键值对

  • 可以通过Key获取到Value,Key不可重复(重复会覆盖)

  • 不支持下标索引

  • 可以修改(增加或删除更新元素等)

  • 支持for循环,不支持while循环

课后练习:升职加薪

有如下员工信息,请使用字典完成数据的记录。

并通过for循环,对所有级别为1级的员工,级别上升1级,薪水增加1000元

姓名

部门

工资

级别

王力鸿

科技部

3000

1

周杰轮

市场部

5000

2

林俊节

市场部

7000

3

张学油

科技部

4000

1

刘德滑

市场部

6000

2

运行后,输出如下信息:

 
 
 
 

全体员工当前信息如下:
{'王力鸿':{'部门':'科技部','工资':3000,'级别':1},'周杰轮':{'部门':'市场部','工资':5000,'级别':2},
'林俊节':{'部门':'市场部','工资':6000,'级别':3},'张学油':{'部门':'科技部','工资':4000,'级别':1},
'刘德滑':{'部门':'市场部','工资':6000,'级别':2}}
全体员工级别为1的员工完成升值加薪操作,操作后:
{'王力鸿':{'部门':'科技部','工资':4000,'级别':2},'周杰轮':{'部门':'市场部','工资':5000,'级别':2},
'林俊节':{'部门':'市场部','工资':6000,'级别':3},'张学油':{'部门':'科技部','工资':5000,'级别':2},
'刘德滑':{'部门':'市场部','工资':6000,'级别':2}}

参考代码:

 
 
 
 

"""
演示字典的课后练习:升职加薪,对所有级别为1级的员工,级别上升1级,薪水增加1000元
"""

# 组织字典记录数据
info_dict = {
"王力鸿": {
"部门": "科技部",
"工资": 3000,
"级别": 1
},
"周杰轮": {
"部门": "市场部",
"工资": 5000,
"级别": 2
},
"林俊节": {
"部门": "市场部",
"工资": 7000,
"级别": 3
},
"张学油": {
"部门": "科技部",
"工资": 4000,
"级别": 1
},
"刘德滑": {
"部门": "市场部",
"工资": 6000,
"级别": 2
}
}

print(f"员工在升值加薪之前的结果:{info_dict}")

# for循环遍历字典
for name in info_dict:
# if条件判断符合条件员工
if info_dict[name]["级别"] == 1:
# 升职加薪操作
# 获取到员工的信息字典
employee_info_dict = info_dict[name]
# 修改员工的信息
employee_info_dict["级别"] = 2 # 级别+1
employee_info_dict["工资"] += 1000 # 工资+1000
# 将员工的信息更新回info_dict
info_dict[name] = employee_info_dict

# 输出结果
print(f"对员工进行升级加薪后的结果是:{info_dict}")

拓展:数据容器对比总结

数据容器分类

数据容器可以从以下视角进行简单的分类:

  • 是否支持下标索引

  • 支持:列表、元组、字符串 - 序列类型

  • 不支持:集合、字典 - 非序列类型

  • 是否支持重复元素:

  • 支持:列表、元组、字符串 - 序列类型

  • 不支持:集合、字典 - 非序列类型

  • 是否可以修改

  • 支持:列表、集合、字典

  • 不支持:元组、字符串

数据容器特点对比

列表

元组

字符串

集合

字典

元素数量

支持多个

支持多个

支持多个

支持多个

支持多个

元素类型

任意

任意

仅字符

任意

Key:Value   Key:除字典外任意类型    Value:任意类型

下标索引

支持

支持

支持

不支持

不支持

重复元素

支持

支持

支持

不支持

不支持

可修改性

支持

不支持

不支持

支持

支持

数据有序

使用场景

可修改、可重复的一批数据记录场景

不可修改、可重复的一批数据记录场景

一串字符的记录场景

不可重复的数据记录场景

以Key检索 Value的数据记录场景

数据容器的通用操作

到目前为止,我们已经掌握了 5 种数据容器。现在,让我们来学习它们的通用操作。虽然每种容器都有自己独特的特点,但它们也有一些通用的操作。

数据容器的通用操作 - 遍历

数据容器尽管各自有各自的特点,但是它们也有通用的一些操作。首先,在遍历上:

  • 5类数据容器都支持for循环遍历

  • 列表、元组、字符串支持while循环,集合、字典不支持(无法下标索引)

尽管遍历的形式各有不同,但是,它们都支持遍历操作。

数据容器的通用统计功能

除了遍历这个共性外,数据容器可以通用非常多的功能方法

  • len(容器)  

统计容器的元素个数

 
 
 
 

my_list = [1, 2, 3]
my_tuple = (1, 2, 3, 4, 5)
my_str = "itiheima"

print(len(my_list)) # 结果3
print(len(my_tuple)) # 结果5
print(len(my_str)) # 结果7

  • max(容器)  

统计容器的最大元素

 
 
 
 

my_list = [1, 2, 3]
my_tuple = (1, 2, 3, 4, 5)
my_str = "itiheima"

print(max(my_list)) # 结果3
print(max(my_tuple)) # 结果5
print(max(my_str)) # 结果t

  • min(容器)

统计容器的最小元素

 
 
 
 

my_list = [1, 2, 3]
my_tuple = (1, 2, 3, 4, 5)
my_str = "itiheima"

print(min(my_list)) # 结果1
print(min(my_tuple)) # 结果1
print(min(my_str)) # 结果a

同学们可能会疑惑,字符串如何确定大小?下一小节讲解。

容器的通用转换功能

除了下标索引这个共性外,还可以通用类型转换

list(容器)        将给定容器转换为列表

tuple(容器)    将给定容器转换为元组

str(容器)         将给定容器转换为字符串

set(容器)         将给定容器转换为集合

容器通用排序功能

通用排序功能 sorted(容器, [reverse=True])  将给定容器进行排序

注意,排序后都会得到列表(list)对象。

容器通用功能总览

功能

描述

通用for循环

遍历容器(字典是遍历key)

max

容器内最大元素

min()

容器内最小元素

len()

容器元素个数

list()

转换为列表

tuple()

转换为元组

str()

转换为字符串

set()

转换为集合

sorted(序列, [reverse=True])

排序,reverse=True表示降序得到一个排好序的列表

字符串大小比较

在上一节课的通用数据容器操作中,我们使用了Min和Max函数,在数据容器中找到最小和最大的元素。在上一节课中,我们有一个问题,那就是字符串如何进行大小比较?在本节课中,我们将讲解这个问题。但在讲解字符串大小比较之前,我们需要先普及一个概念,这就是ASCII码表。在我们的程序中,字符串中使用的字符可以是大写或小写的英文字母、数字以及特殊符号,如感叹号、斜杠、竖杠、“@”符号、井号、空格等。每个字符都有其对应的ASCII码表值,因此字符串的比较基于字符所对应的数字码值的大小来进行。

字符串进行比较就是基于数字的码值大小进行比较的。

下面是一个典型的ASCII码表,其中我们可以找到我们所使用的一系列符号或字符对应的码值。例如,数字0123456789对应的码值从48到57,我们经常使用的大写英文字母从A到Z,对应的码值在65到90之间,小写英文字母从a到z,对应的码值在97到122之间。因此,我们常用字符的码值都可以在表中找到,因此,字符串的大小比较就很容易理解了。

For example, a lowercase a and an uppercase A, we say who is bigger and who is smaller, in fact, they are compared by code value. The lowercase a and the uppercase A, whichever is bigger, will also find that the code value of the lowercase a is 97, which is larger than the 65 of the uppercase A, so the benchmark for character string comparison is the code value of the ASCII code table. With this concept in mind, let's look at how strings are compared.

string comparison

Strings are compared bit by bit, that is, bit by bit is compared, as long as one bit is larger, the whole is larger.

 
 
 
 

"""
Demo string size comparison
"""

# abc compares abd
print(f"abd is greater than abc, result: {'abd' > 'abc'}")
#a compares ab
print(f"ab is greater than a, result: {'ab' > 'a'}")
# compare a to A
print(f"a is greater than A, result: {'a' > 'A'}")
# key1 compares key2
print(f"key2 > key1, result: {'key2' > 'key1'}")

output result

 
 
 
 

abd is greater than abc, result: True
ab is greater than a, result: True
a is greater than A, result: True
key2 > key1, result: True

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130618126