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

Pick up your hands to learn Python once the list is completed, python will be half

編輯:Python

Four 、 List one is finished ,Python Half of it

==================

4.1 What is a list


list , First remember English is list , It is Python A data type that can dynamically add and delete content in , It's made up of a series of elements . To put it bluntly, a list is a container that combines multiple variables together .

Many articles will look for a programming concept similar to lists , Generally speaking Python In other languages Array equally , But for students who don't have any programming concepts , Array It's also a strange concept . In fact, you can simply understand it ,Python The list in is a container , You can put variables of any data type in it .

4.1.1 List definition

The format of the list definition is as follows

my_list = [ Elements 1, Elements 2, Elements 3...]

Every piece of data in a list is called an element or an item , List with [] The parcel , Every element is in English , Separate , Lists can be printed out directly .

my_list = ["apple", "orange", "grape", "pear"]
print(my_list)

The elements in the list can be of the same data type , It can also be different data types , So the list nesting list is also possible .

my_list = [1, "orange", True, 1.0, [1, 2, 3]]
print(my_list)

4.1.2 List reading

To read a list, you need to learn two nouns first , One is the index , The other is the subscript , The two words have the same meaning , It's all about getting the elements in the list exactly . Index can be simply understood as the concept of serial number .

The first thing you need to learn is that the index in the list is from 0 At the beginning , The concept was a little awkward when it first came into contact , It will be much better if you are familiar with it . Just like we count numbers from 1 Starting number , All of a sudden, it needs to be changed from 0 Start counting , You need a period of adjustment .

For example, take a look at the list , Try to read the index of each element in Chinese .

my_list = ["apple", "orange", "grape", "pear"]

The index for 0 The element of is a string apple, The index for 1 The element of is a string orange, By analogy .

The syntax format of list reading is as follows :

# List name [ Indexes ]
my_list[i]

The above is translated into Python The code is :

my_list = ["apple", "orange", "grape", "pear"]
print(" The index for 0 The element is :", my_list[0])
print(" The index for 1 The element is :", my_list[1])
print(" The index for 2 The element is :", my_list[2])
print(" The index for 3 The element is :", my_list[3])

When you get elements by index , Be sure to note that the index is from 0 At the beginning , from 0 At the beginning , Though I write it over and over again , But it's still easy to forget ...... alas ~

Except that the index is positive , It can also be negative , The index to get the last element of the list is -1, The code is as follows :

nums = [1,2,3,4,5,6]
print(" The last element in the list is :",nums[-1])

According to the order ,-1 Represents the last element ,-2 Means the last 2 term ...

4.1.3 List slice

When writing a program, the operation of the list often has the following scenarios .

  • obtain 1~3 Item element ;
  • obtain 4~7 Item element ;
  • For the first 1,3,5... Item element .

These are translated into the actual encoding of the list , It's called slicing , That's what you're doing in your head right now .

The specific syntax format is as follows :

# Read from index m To n-1 List elements of
my_list[m:n]
# Before reading the list n Item element
my_list[:n]
# Read the list from m Elements from the beginning to the end
my_list[m:]
# interval s, Read from m To n List elements of
my_list[m:n:s]

The above contents are reflected in the code and are shown as follows , This section is presented in the code as follows , Pay special attention to m And n The value of .

my_list = ["a","b","c","d","e","f"]
# Output ['a', 'b', 'c'] Be careful a,b,c Their indexes are respectively 0,1,2
print(my_list[0:3])
# Output ['b', 'c', 'd', 'e'] Be careful b,c,d,e The subscripts are 1,2,3,4
print(my_list[1:5])
# Output ['b', 'c', 'd', 'e', 'f']
print(my_list[1:])
# Output ['a', 'b', 'c', 'd', 'e']
print(my_list[:5])
# Output ['b', 'd'] From the index 1 To the index 3, interval 1 The index is
print(my_list[1:4:2])

List slicing in the following Python Learning belongs to a very important knowledge point , The core is to figure out how the index corresponds to each element in the list .

4.1.4 List dependent built-in functions

stay Python The common built-in functions related to lists are 4 individual , To get the maximum value max、 minimum value min、 Sum up sum And get the number of list elements len.

Maximum and minimum

Use max And min Function can directly get the maximum and minimum values in the list , This function uses some precautions need to understand next , Specific or reference code :

my_list1 = ["a","b","c","d","e","f"]
my_list2 = [1,2,3,4,5,6]
my_list3 = ["a",1,2,3,4]
# Output f
print(max(my_list1))
# Output 6
print(max(my_list2))
# Report errors
print(max(my_list3))

The above code found at run time , front 2 The list can output the maximum value , But the third one is wrong , This is because max And min It can only be used for lists whose elements are all numbers or strings , If there are other data types in the list or the number is mixed with the string, an error will be reported .

min Usage and max Exactly the same , Not trying to write code .

Sum up

sum Function to get the sum of the list elements , But you need to pay attention to sum Can't be used for non numerical elements , In other words, the following code is wrong .

my_list1 = ["a","b","c","d","e","f"]
print(sum(my_list1))

Get the number of list elements

This function is used very frequently , In many places, you need to get the number of list elements , Use len Function , Because the code is very simple , Just test yourself .

4.1.5 Modification and deletion of list elements

For a variable of list data type , It can modify and delete elements , This is the list mentioned at the beginning of this article Python A data type that can dynamically add and delete content in ( This section cannot be added to the list dynamically yet , It will be explained later ).

The elements of the list can be modified through the index .

my_list1 = ["a","b","c","d","e","f"]
print(" List before modification ",my_list1)
my_list1[4] = " Eraser "
print(" Modified list ",my_list1)

There are two ways to delete a list element , In short, one is to delete a single element , One is to delete multiple elements . Deletion is highly associated with list slicing , The following code can be compared for learning .

my_list1 = ["a","b","c","d","e","f"]
# Delete an element by index
del my_list1[0]
print(my_list1)
my_list1 = ["a","b","c","d","e","f"]
# Delete list interval elements by index
del my_list1[0:3]
print(my_list1)
my_list1 = ["a","b","c","d","e","f"]
# Delete list interval elements by index
del my_list1[0:3:2]
print(my_list1)

The keyword used in the delete operation is del, The key point, I believe you have also found , Find the element through the index and then go through del Remove elements .

Above contents , Note that the operation is on the elements in the list , Next we'll learn how to manipulate a complete list .

4.1.6 List together , Multiply , Delete

stay Python You can directly add and multiply the list in , The addition of a list to a list can be understood as a connection of a list , The code is as follows :

my_list1 = ["a","b"]
my_list2 = ["c"]
my_list3 = my_list1 + my_list2
print(my_list3)

Any number of lists directly if you use “+” To operate , Then these lists will be linked together to form a new large list .

A list can be multiplied by a number , Repeat the previous list more than once , For example, the following code :

my_list1 = ["a","b"]
my_list2 = ["c"]
my_list3 = my_list1 * 4
# The output is ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
print(my_list3)

The above code uses [a,b] * 4 The result is a list [a,b] It's repeated 4 Time .

4.2 First time to know Python object-oriented


Python Is an object-oriented programming language , So in Python All the data in is an object , For example, we learned about integers 、 Floating point numbers 、 character string 、 Lists are objects , Don't explain too much about the concept of object orientation ( After all, it's useless to explain now , Specifically, the object-oriented part will be explained ).

We can design some for all kinds of objects Method , these Method Also in a broad sense function , Doesn't it sound a little bit convoluted , stay Python Some methods have been built into some basic objects in , Starting with the list, we'll step into the built-in methods of objects .

Object method call syntax format is :

 object . Method ()

4.2.1 Methods of string objects

You have to know first that in Python Any data in is an object , After declaring a string variable , Then this string variable is an object , If it is an object, there will be an object method . The common methods of string are :

  1. lower Convert string to lowercase
  2. upper Convert strings to uppercase
  3. title Capitalize the initial of a string , The rest are in lowercase
  4. rstrip Remove the white space on the right side of the string
  5. lstrip Remove the left margin of the string
  6. strip Remove white space on both sides of the string

String case description

my_str = "good moring"
my_strU = my_str.upper()
my_strL = my_str.lower()
my_strT = my_str.title()
# Capitalization
print(my_strU)
# A lowercase letter
print(my_strL)
# title case
print(my_strT)

The output corresponds to the following :

GOOD MORING
good moring
Good Moring

Removing white space at the beginning or end of a string is a very useful way , It's up to you to do it yourself . Code can refer to my_str.strip() .

4.2.1 Quick access to system built-in methods

In actual development , It's hard to remember all the methods of an object , For erasers, when you write code, you have to use the manual , There are too many ways to remember , Just remember the usual ones , How to query all the methods of an object , It uses a built-in function dir.

for example , You want to know all the methods of a string object , You can write the following code .

my_str = "good moring"
print(dir(my_str))

After the code runs , You will get the following , The content in the red box is the method mentioned just now .

For how a method is used , You can call the previously learned help Built in functions for learning , The syntax is as follows :

help( object . Method )

For example, get the string object rfind Method .

my_str = "good moring"
print(help(my_str.rfind))

give the result as follows , A little reading will show you rfind How to use the method .

How to look at the list

Because we will continue to learn the list method , So let's do a simple presentation first .

my_list1 = ["a","b"]
print(dir(my_list1))

The following content of this blog will explain the method of the red box part , There must be people who care about what's not in the red box, with two _ What begins with , They are also methods , But it's not time to learn them yet .

4.3 Add or delete list elements by method


4.3.1 Add elements to the list

The following scenarios often appear when operating lists , You need to add elements to the existing list , For example, the original list has an element , Now I want to add two . If set directly , The index value exceeds the length of the list , Note that this error often occurs when manipulating lists .

my_list = ["apple", "orange", "grape"]
my_list[3] = "pear"

The error prompt is IndexError: list assignment index out of range , Here's the thing to notice , Be familiar with some common mistakes or code in the learning process , So that when these errors appear, we can quickly find the cause .

Append elements to the list ,Python A method is built into the list object in , The specific format is as follows .

my_list.append(" New elements ")

For example, you can declare an empty list next , Then add elements to the list .

my_list = []
my_list.append("pear")
my_list.append("apple")
my_list.append("orange")
print(my_list)

adopt append Method , Each time an element is appended to the end of the list , With this method, you can expand the list without restriction .

4.3.2 List inserts elements

append The method is to insert elements at the end of the list , How to insert elements anywhere is a new way , The name is called insert, The syntax is as follows :

my_list.insert( Index position ," New elements ")

Try to index 1, Indexes 2, Indexes 0 The location of the insert element , The code is as follows :

my_list = ["pear", "apple", "orange"]
my_list.insert(0, " Insert ")
print(my_list)
my_list = ["pear", "apple", "orange"]
my_list.insert(2, " Insert ")
print(my_list)

Note here that when the index exceeds the length of the list , Default insert end .

4.3.3 Delete list elements

A way to delete list elements has been described in the previous section , By keyword del, One problem with this method is that the deleted elements are not retrieved after deleting them . The next step is to solve the problem , You will be able to get the deleted value , The method is pop , The syntax is as follows :

item = my_list.pop()
item = my_list.pop( Indexes )

Pay attention to pop Method can carry an index value , Directly delete the element at the index position , If there is no default delete the last item . Variable item Used to get deleted values . Notice when this method removes elements , The index cannot exceed the length of the list .

my_list = ["pear", "apple", "orange"]
item = my_list.pop()
print(item)
print(" After deleting elements ")
print(my_list)

The code runs as :

orange
After deleting elements
['pear', 'apple']

pop The method is to delete the elements according to the index , You can also delete the specified element directly , The way to do it is remove, The syntax format of this method is as follows .

my_list.remove( Element content to be deleted )

Be careful remove After deleting elements , No deleted elements are returned , There is also a problem if the element to be deleted is not in the list , Will prompt code error .

If the element to be deleted appears more than one in the list , By default, only the first one is deleted , If you want to delete more than one , We need to use the following cycle knowledge .

4.4 Sort the list


In addition to adding, deleting and modifying the list, it also involves sorting related contents , This operation is also very simple for list objects , Use a fixed method .

4.4.1 sort Sort

sort Method to sort the list elements , Default from small to large , Of course, it can be changed from big to small , This method is usually used to sort the list of pure numbers or English characters , If the data types of elements in the list are complex , This method is no longer applicable , You need to pay attention to .

sort The syntax of the method is as follows :

my_list.sort()

Declare a list where all elements are numbers , And then sort it .

my_list = [3, 4, 1, 2, 9, 8, 7]
print(" Before ordering :", my_list)
my_list.sort()
print(" After ordering :", my_list)

The output is as follows :

 Before ordering : [3, 4, 1, 2, 9, 8, 7]
After ordering : [1, 2, 3, 4, 7, 8, 9]

If you want to sort it in descending order , Just add parameters ( The concept of parameters will be studied later )reverse=True that will do .

my_list = [3, 4, 1, 2, 9, 8, 7]
print(" Before ordering :", my_list)
my_list.sort(reverse=True)
print(" After ordering :", my_list)

I hope you can test the sorting results of English strings , Attention should be paid to sorting the list of English characters , It is suggested to change all English strings to lowercase .

Note that the above sort After sorting the method, the order of the elements in the original list is modified , That is to say my_list The order of the list , If you don't want to change the order of the original list , Want to create a new list , The following methods are needed .

4.4.2 sorted Sort

sort Sorting causes the order of the list elements to be changed permanently , Most of the time, you don't need to modify the original list , In this case, we need to rely on sorted function , Be careful sorted Is a built-in function , It's not a method of listing objects , in other words sorted Many objects can be sorted .

sorted The syntax format of the function is as follows :

sorted( To sort list ) # positive sequence , From small to large
sorted( To sort list ,reverse=True) # The reverse , From big to small 

This function will return a new list after use , You can receive it with a new variable , The specific code is as follows :

my_list = [3, 4, 1, 2, 9, 8, 7]
print(" Before ordering :", my_list)
new_list = sorted(my_list)
print(" After ordering :", my_list)
print(" After ordering :", new_list)

Note that after sorting, the new variable is new_list For the original my_list The order of the elements in the list does not affect .

4.5 List other methods


4.5.1 List search element index

adopt index Method to get the index value of the first occurrence of something in the list , The format is as follows :

 Index value = my_list.index( Value to be found )

Note that if the index value is not retrieved , It will give you an error .

my_list = [3, 4, 1, 2, 9, 8, 7]
ke = my_list.index(4)
ke = my_list.index(10)
print(ke)

4.5.2 The list counts the number of occurrences of elements

adopt count Method to get the number of times a particular element of a list appears , Its syntax is as follows :

 frequency = my_list.count( Value to be found )

This method also returns when the value to be looked up is not found in the list 0.

my_list = [3, 4, 3, 2, 3, 8, 7]
nums = my_list.count(3)
print(nums)

4.5.3 List to string

adopt join Method can combine all the elements in a list into a string , The syntax is as follows :

 Connection string .join( List to be converted )

In fact, the method should be exactly A method of string object .

my_list = ["pear", "apple", "orange"]
my_str = "#".join(my_list)
print(my_str)

When using this method, attention should be paid to , All elements in the list must be strings , Otherwise expected str instance, int found error .

4.5.4 List append list

append Method can append elements to the list ,extend You can append a list to a list , It's equivalent to connecting two lists .

 list 1.extend( list 2)

Note that the appended list is appended at the end of the original list by default , So after appending, the elements in the original list have changed .

my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
my_list1.extend(my_list2)
print(my_list1)

4.6 Multidimensional list


The elements in the list can be of any data type , So it's OK to list nested lists .

my_list = [1,2,3,[4,5,6]]

This method needs to pay attention to when getting the elements in the nested list , You need to get it by hierarchy , For example, you want to get elements 5, The first step is to get the... In the outermost list 4 Item element , namely my_list[3], Then get it and then get it. The index position is 1 The elements of , namely my_list[3][1], Specific code can be tried on your own , You can also use nested lists in the inner list , Go on indefinitely .

4.7 Special list string


Now let's go back to the string format of "abcsdasa", You can think of a string as a list of characters , It's also known as a sequence of characters ( An ordered list ), Strings are not exactly equivalent to lists , Because you can't modify a single element in a string .

4.7.1 String indexing and slicing

Strings can also be indexed to access an element , The index is used the same way as the list , For example, the following code :

my_str = "abcdefghi"
print(my_str[5])
print(my_str[4])
print(my_str[3])

List slicing can also be used for Strings , Equivalent to getting a string substring .

4.7.2 Partial functions and methods that can be used for Strings

List related built-in methods , for example len、max、min It can also be used for strings , You can try it yourself .

4.7.3 Convert string to list

With built-in functions list You can convert a string to a list , In other words, each character in the string is disassembled .

my_str = "abcdefghi"
print(list(my_str))

The output content is :

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

4.8 The summary of this blog


List in Python The base part is a very important data type , When writing this blog, I was also considering whether to include all the contents , It turns out there's too much content , A lot of it has a strong correlation with what happens later , In this blog, I also learned some of the simplest concepts of object-oriented .


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