当前位置:网站首页>3-list introduction

3-list introduction

2022-06-24 07:55:00 axinawang

Lists allow you to store groups of information in one place , It can contain just a few elements , It can also contain millions of elements .

3.1 What is the list

A list consists of a series of elements arranged in a specific order .

Assign a plural name to the list .

stay Python in , In square brackets ([]) Represents a list , And separate the elements with commas .

for example :

bicycles = ['trek', 'cannondale', 'redline', 'specialized']

Python The internal representation of the list will be printed , Include brackets . 

3.1.1 Access list elements

Access list elements , You can indicate the name of the list , And then point out the index of the element , And put the latter in square brackets .

for example :bicycles[0]

3.1.2 Index from 0 instead of 1 Start

stay Python in , The index of the first list element is 0, instead of 1.

By specifying the index as -1, Allowing Python Returns the last list element , This Convention also applies to other negative indexes .

3.1.3 Use the values in the list

You can use the values in the list just like other variables .

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."

print(message)

Give it a try

Please try to write some short programs to complete the following exercises , To get some use Python First hand experience of the list . You may need to create a folder for each chapter , Store the program written to complete the exercises of each chapter in a neat and orderly manner .

practice 3-1: full name Store the names of some friends in a list , And named it names. Access each element in the list in turn , To print out the name of each friend .

practice 3-2: greetings Continue to use the exercise 3-1 List in , But don't print every friend's name , And print a message for each person . Each message contains the same greeting , But the head is the name of the corresponding friend .

practice 3-3: Own list Think about the way you like to commute , Such as riding a motorcycle or driving a car , And create a list of multiple commutes . Print a series of declarations about these commutes based on this list , Here is an example .I would like to own a Honda motorcycle.

3.2 modify 、 Add and remove elements

3.2.1 Modify list elements

To modify a list element , You can specify the list name and the index of the element to be modified , Then specify the new value of the element .

Example :bicycles[0]=‘ Giante ’

3.2.2 Add elements to the list

Add elements at the end of the list : Method append( Elements )

Example :motorcycles.append('jialing')

Insert elements in the list : Usage method insert( Indexes , Elements ) You can add new elements anywhere in the list

Example :motorcycles.insert(0,'longxin')

3.2.3 Remove elements from the list

Use del Statement delete element :del motorcycles[1]

Usage method pop() Remove elements : Method pop() Delete element at end of list , And allow you to continue to use it .

Elements anywhere in the pop-up list :motorcycles.pop( Indexes )

Delete elements... Based on values : Method remove( value ) Delete only the first specified value ,too_expensive = 'ducati'
motorcycles.remove(too_expensive)

Give it a try

The following exercise is better than 2 The exercises in chapter are more complicated , But it gives you the opportunity to use the list in the various ways described above .

practice 3-4: Guest list If you can invite anyone to dinner ( Whether living or dead ), Who are you going to invite ? Please create a list , Include at least three people you want to invite , Then use this list to print messages , Invite these people to dinner with you .

practice 3-5: Change the guest list You just learned that a guest couldn't keep the appointment , So we need to invite another guest .▲ To complete the exercise 3-4 Based on the program written in , Add a clause at the end of the program print sentence , Point out which guest can't keep the appointment .▲ Change the guest list , Replace the names of the guests who are unable to attend the appointment with the names of the newly invited guests .▲ Print a series of messages again , Send an invitation to each guest on the list .

practice 3-6: Add guests You just found a bigger table , It can accommodate more guests . Please think about the three other guests you would like to invite .

▲ To complete the exercise 3-4 Or practice 3-5 Based on the program written in , Add a clause at the end of the program print sentence , Point out that you found a bigger table .▲ Use insert() Add a new guest to the beginning of the list .▲ Use insert() Add another new guest to the middle of the list .▲ Use append() Add a new guest to the end of the list .▲ Print a series of messages , Send an invitation to each guest on the list .

practice 3-7: Reduce the list You just learned that the newly purchased table can't be delivered in time , So we can only invite two guests .▲ To complete the exercise 3-6 Based on the program written in , Add a line of code to the end of the program , Print a message that you can only invite two guests to dinner .▲ Use pop() Constantly deleting guests from the list , Until there were only two guests . Every time a guest pops up from the list , Print a message , Let the guest know that you are sorry , Can't invite him to dinner .▲ For each of the remaining two guests , Print a message , Point out that he is still among the invitees .▲ Use del Remove the last two guests from the list , Make the list empty . Print the list , The list was indeed empty at the end of the verification process .

3.3 Organization list

3.3.1 Usage method sort() Sort the list permanently

Ascending : list .sort()

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

reverse : list .sort(reverse=true)

cars.sort(reverse=True)

3.3.2 Using functions sorted() Sort the list temporarily

print(sorted(cars))

  Inversion also uses parameters reverse=true

3.3.3 Print the list backwards

To reverse the order of the list elements , Serviceable method reverse():cars.reverse()

3.3.4 Determine the length of the list

Using functions len() You can quickly learn the length of the list .

Give it a try

practice 3-8: Have the whole world in view Think of at least 5 A place where you're eager to travel . Store these places in a list , And make sure that the elements are not in alphabetical order . Print the list in its original order . Don't think about whether the output is neat or not , Just print the original Python list .▲ Use sorted() Print this list in alphabetical order , At the same time, don't modify it .▲ Print the list again , Check that the order has not changed .▲ Use sorted() Print the list in reverse order , At the same time, don't modify it .▲ Print the list again , Check that the order has not changed .▲ Use reverse() Change the order of the list elements . Print the list , Check that the order has changed .▲ Use reverse() Change the order of the list elements again . Print the list , Verify that the original order has been restored .▲ Use sort() Modify the list , To arrange its elements in alphabetical order . Print the list , Check that the order has changed .▲ Use sort() Modify the list , Arrange its elements in reverse order of alphabet . Print the list , Check that the order has changed .

practice 3-9: Dinner guests After completing the exercise 3-4~ practice 3-7 In one of the programs written when , Use len() Print a message , Point out how many guests you invited to dinner . practice 3-10: Try using various functions Think about what you can store in a list , Like mountains and rivers 、 The river 、 Country 、 City 、 Language or anything you like . Write a program , Create a list of these elements , then , For each function introduced in this chapter , Use this list at least once .

3.4 Avoid index errors when using lists

When the index exceeds the index range , An index error will occur .

Traceback (most recent call last):
  File "E:\...\motorcycles.py", line 12, in <module>
    print(motorcycles[9])
IndexError: list index out of range

  Or when the list is empty , Use index -1 To access the last element .

Traceback (most recent call last):
  File "E:\...\motorcycles.py", line 12, in <module>
    print(motorcycles[-1])
IndexError: list index out of range

Be careful When an index error occurs and no solution is found , Try printing the list or its length . The list may be quite different from what you think , This is especially true when the program processes it dynamically . By looking at the list or the number of elements it contains , It can help you find out this logical error .

Give it a try

practice 3-11: Intentional error If you haven't encountered an index error in your program , Just try to cause one of these errors . In one of your programs , Modify the index , To cause an index error . Before closing the program , Be sure to eliminate this error .

3.5 Summary

In this chapter , You studied. : What a list is and how to use its elements ; How to define a list and how to add or delete elements ; How to permanently sort a list , And how to sort the list temporarily ; How to determine the length of the list , And how to avoid index errors when using lists .

原网站

版权声明
本文为[axinawang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240409227931.html