当前位置:网站首页>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 rangeOr 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 rangeBe 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 .
边栏推荐
- How to realize multi protocol video capture and output in video surveillance system?
- Using kubeconfig files to organize cluster access
- ImportError: cannot import name ‘process_pdf‘ from ‘pdfminer.pdfinterp‘错误完全解决
- 运行npm run eject报错解决方法
- OpenGauss数据库在 CentOS 上的实践,配置篇
- Alibaba cloud full link data governance
- AWTK 最新动态:Grid 控件新用法
- 后疫情时代下,家庭服务机器人行业才刚启航
- 常见的数组封装
- 闲谈:3AC到底发生了什么?
猜你喜欢
![[C language] system date & time](/img/de/faf397732bfa4920a8ed68df5dbc48.png)
[C language] system date & time

Mousse shares listed on Shenzhen Stock Exchange: gross profit margin continued to decline, and marketing failed in the first quarter of 2022

第 2 篇:繪制一個窗口

Keep one decimal place and two decimal places

鸿蒙os开发三

关于h5页面苹果手机使用fixed定位tabbar最底部时遮挡内容问题

Alibaba cloud full link data governance

本地备份和还原 SQL Server 数据库

希尔伯特-黄变换

Specify IP when calling feign interface
随机推荐
用Ngrok 配置属于自己的免费外网域名
Take my brother to make a real-time Leaderboard
Basics of reptile B1 - scrapy (learning notes of station B)
没有专业背景,还有机会成为机器学习工程师吗?
云开发谁是卧底小程序源码
UE common console commands
Inline element, block element, inline block element
SVN实测常用操作-记录操作大全
Cold thinking on the hot track: multiplier effect is the fundamental requirement of East West calculation
duilib 显示内存图片
第 2 篇:繪制一個窗口
线程的支持
1-4metasploitable2介绍
ImportError: cannot import name ‘process_pdf‘ from ‘pdfminer.pdfinterp‘错误完全解决
These dependencies were not found: * core JS / modules / es6 array. Fill in XXX
第 2 篇:绘制一个窗口
.jar中没有主清单属性
第 3 篇:绘制三角形
希尔伯特-黄变换
L1-019 谁先倒 (15 分)