Python data container [list]

Python data container

Data container in Python:

A data type that can hold multiple copies of data. Each copy of data is called It is1 elements

Each element can beany type of data, such as string, number, Boolean, etc.

Data containers vary according to characteristics, such as:

Whether repeated elements are supported, whether they can be modified, and whether they are in order, etc.

Separable 为5类、separation is: list), element group (< /span>)dict), Dictionary (set), set (str), character skewer (tuple

 

They each have their own characteristics, but they all meet the characteristics of being able to accommodate multiple elements .

list definition

Why do you need a list

A person's name(TOM) We wantto store in the program a string that can be used Variable, butif a class 1 has 00 students, and everyone’s name needs to be stored, how should it be written? program? Declare100 variables?

It seems very troublesome at this time, but in factWe can just use a list, which can store multiple data at a time.

list definition

Each data in the list is called an element. is marked with []. Between each element in the list, Comma separated

Definition syntax:

Use[] to define a list:

name_list = ['eternallei','Eternallei']
print(name_list)
print(type(name_list))

Output result:

Definition of nested lists

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

Output result:

What you need to know is that lists can store multiple data at one time, and can be of different data types and support nesting.

subscript (index) of the list 

So how do we get the data at a specific position from the list?

Can be used:Lower titleIndex

As shown in the figure, each element in the list has its position subscript index, from front to back, from 0< /span>Start and increase in sequence

We only need to follow the subscript index to get the element at the corresponding position.

# 语法:列表[下标索引]

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

result:

Subscript (index) of a nested list

We can also index the nested list just now

As shown in the figure, then its subscript has2 levels:

my_list = [[5, 2, 0], [1, 3, 1, 4]]
# 取内层第一个的第一个元素
print(my_list[0][0])    # 结果为:5
# 取内层第二个的第三个元素
print(my_list[1][3])    # 结果为:4
# 取内层第一个的第一个元素
print(my_list[-2][-3])  # 结果为:5

The two directions of the index:The direction from front to back, the number starts from 0In the direction of increment, the direction from back to front, the number starts from -1Start decreasing

Common operations (methods) on lists

In addition to being able to: define and use subscript indexes to obtain values, lists can

Lists also provide a range of functions:

Insert elements, delete elements, clear lists, modify elements, count the number of elements, etc. We call these functions:List methods

List query 

We know that a function is an encapsulated unit of code that provides specific functionality.

InPython, if the function is defined asclass (class) member, then the function will be called: method

function:

method:

Methods and functions have the same functions. There are incoming parameters and return values, but the method usage format is different:

Function usage:

Method usage:

Regarding the definition of classes and methods, you only need to know how to use methods first, and we will learn about them later.

Find the index of an element:

Function: Find the subscript of the specified element in the list. If it cannot be found, a ValueError will be reported.

Language: Column table.index(Element) 

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

# 查询字符所在下标索引

my_list = ['eternallei','Eternallei']
print(my_list.index('Eternallei'))   # 结果为:1

Count how many elements there are in the list

Language:len(column table)

You can get an int number representing the number of elements in the list

List modification function

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

Language: column table[bottom list] =

You can use the above syntax to directly reassign (modify) the value of the specified subscript (either forward or reverse subscript)

# 使用正向下标

my_list = [5, 2, 0]
my_list[2] = 1
print(my_list)    # 结果:[5, 2, 1]

# 使用反向下标

my_list = [5, 2, 0]
my_list[-1] = 1
print(my_list)    # 结果:[5, 2, 1]

Insert elements:

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

# 插入元素

my_list = [5, 2, 0]
# 在下标索引3插入字符串,因为没有所以就在0后面做到了追加效果...
my_list.insert(3, "郭佳佳")
print(my_list)

Append elements:

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

# 追加元素

my_list = [5, 2, 0]
my_list.append(1)
print(my_list)    # 结果:[5, 2, 0, 1]

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

Additional element method2:

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

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

Delete elements:

language1: del column table [bottom]

Language2:Column table.pop(Bottom )

# 删除元素

my_list = [5, 2, 0]
del my_list[0]
print(my_list)   # 结果:[2, 0]

my_list = [5, 2, 0]
my_list.pop(0)
print(my_list)   # 结果:[2, 0]

Remove the first occurrence of an element in the list

Language: Column table.remove(Element)

Clear list contents

Language: Column table.clear() 

 Count the number of elements in a list

Language: Column table.count(Element)

List Methods - Overview

serial number

Usage

effect

1

column table.append(element)

Append an element to the list

2

column table.extend(container)

Take out the contents of the data container one by one and append them to the end of the list

3

column table.insert(bottom, element< /span>)

At the specified subscript, insert the specified element

4

del column table[bottom]

Delete the specified subscript element from the list

5

column table.pop(bottom)

DeleteDelete the specified subscript element from the list

6

column table.remove(element)

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

7

column table.clear()

clear the list

8

column table.count(element)

Count the number of times this element appears in the list

9

Column table.index(Element)

Find the subscript of the specified element in the list

Not found errorValueError

10

len(column table)

Count how many elements are in the container

You can see that there are many functional methods, but there is no need to memorize them. What you need to do is to have a vague impression and know that there is such a usage. Check it out whenever you need it.

To summarize, the list has the following characteristics:

can accommodate multiple elements (the upper limit is 2**63-1, 9223372036854775807)

Can accommodate different types of elements (mixed)

Data is stored in order (with subscripted serial numbers)

Allow duplicate data to exist

Can be modified (add or delete elements, etc.) 

encyclopedia - whilecirculation

Since the data container can store multiple elements, there will be a need to sequentially remove elements from the container for operation.

The behavior of taking out the elements in the container for processing in sequence is called:traversal and iteration.

You can use the while loop you learned earlierlist [subscript] Remove it

How the loop condition controls the definition of a variable to represent the subscript, starting from 0

The loop condition is: Subscript value < Number of elements in the list

encyclopedia - forcirculation

In addition to while loop, Python also has Another form of loop: for loop.

Compared withwhile, for loop is more suitable for lists Wait for the data container to be traversed.

grammar:

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

In each loop, we can process temporary variables (elements).

 Each loop takes out elements from the list and assigns them to variablesi, providing operations

As a result, you can try it yourself

whilecirculation sumforcirculation ratio

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

On loop control:

whileLoopYou can customize the loop conditions and control them yourself

forLoopYou cannot customize the loop conditions, you can only retrieve data from the container one by one

On an infinite loop:

while loopcan achieve infinite loop through conditional control

For loop theoretically is not possible, because the capacity of the container being traversed 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 traversing data containers or simple fixed-number loop scenarios.

In comparisonthe for loop is simpler, but while is more flexible, so for Elements are taken out and processed sequentially from the container, and while is used in any scenario that requires looping

Guess you like

Origin blog.csdn.net/m0_59795797/article/details/134387092