Detailed explanation of python lists
Free learning recommendations: python video tutorial
python:list
- 1. Sequence
- 1.1. Basic concepts
- 1.2. Index
- 1.3. Practical application
- 2. List
- 2.1. The concept of list
- 2.2. The use of list
- 3. Slicing
- 3.1. Concept of slicing
- 3.2. Grammar
- 3.3. Practical application
- 4. Common operations
- 4.1 Operation and instructions
- 4.2 Practical application
- 5. Modify the list
- 5.1. Direct modification
- 5.2. Slice modification
- 5.3. Delete keyword
- 6. List method
- 6.1 Method and description
- 6.2 Practical application
- ##6.2.1 , Add method
- 6.2.2, Delete method
- 6.2.4, Reverse list
- 6.2.1, Sort
7. Supplement to conditional statements (for loop) - 7.1. Basic concepts
- 7.2. For loop syntax
- 7.2 Usage of range
8. Homework- ##8.1. Now there is a = [1,2,3,4,5 ,6] Use multiple ways to reverse the list ([6,5,4,3,2,1]) and write the derivation process
- 8.2. Give the user 9 chances to guess 1 - 10 Numbers are randomly guessed.
- 8.3. There are two lists lst1 = [11, 22, 33] lst2 = [22, 33, 44] to obtain elements with the same content
- 8.4. There are 8 teachers now, 3 offices, requiring 8 teachers to be randomly assigned to three offices
- 9.1. Find the value of 1/1-1/2 1/3-1/4 1/5... 1/99 - 1/100
- 9.2. Calculate the sum of the following sequence. 1/3 3/5 5/7 .... 97/99
- 9.3. Input 2 values, determine how many prime numbers there are between them, and output all prime numbers
1. Sequence
I mentioned it before, but I’ll mention it again because it’s veryimportant, important, important
1.1. Basic concepts, so important things should be said three times. Friends who are interested can click on the blog link to have a look. Of course, this article also talks about slicing the list
Sequence is the most basic data structure in Python.
- Sequence is used to save
. All data has a unique position (index) in the sequence and the data in the sequence will Indexes are allocated in the order they are addedData structure refers to the way data is stored in the computerThe sequence is
a data structure called a container
. Sequences (for example: lists, tuples) and maps (for example: dictionaries).
Each element in the sequence has a number, while
each element in the map has a name (key ), and a collection is neither a container of sequence type nor a mapped type.
Sequences can perform some special operations: indexing, slicing, addition, multiplication, and checking whether an element belongs to the sequence. In addition, python can also calculate the length of a sequence and find the built-in functions of the maximum function and the minimum function.
- Classification of sequences:
-
Can Mutable sequence (the elements in the sequence can be changed): such as list
- Immutable sequence (the elements in the sequence cannot be changed): such as string (str) tuple (tuple)
1.2. Index
Array index, the array index mechanism refers to using square brackets ([]) plus a serial number to reference a single Array elements have many uses, such as extracting elements, selecting several elements of an array, and even assigning them a new value.
Here is the index of a list to show, for example arraya=['a','b','c','d','e','f','g','h ','i']
'b' | 'c' | 'd' | 'e' | 'f | 'g' | 'h' | 'i' | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Number (reverse order) | |||||||||||||||||||||||||||||||||||||||||
-8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Operation | Instructions |
---|---|
You can splice two lists into one list | |
* | You can repeat the list a specified number of times (Note that two lists cannot be multiplied, and must be multiplied with integers) |
in | is used to check whether the specified element is in the list |
not in | is used to check whether the specified element is not in the list |
len() | Get the number of elements in the list |
max() | Get the maximum value in the list |
min() | Get the minimum value in the list |
The first parameter gets the position of the specified element in the list | The second parameter indicates the starting position of the search The third parameter indicates the end position of the search |
Count the number of times the specified element appears in the list | |
Shallow copy list | |
operator module | Compare the elements of two lists
方法 | 说明 |
---|---|
append() | 像列表的最后添加一个元素 |
insert(arg1,arg2) | 像列表指定位置插入一个元素 参数1:要插入的位置 参数2:要插入的元素 |
extend(iterable) | 使用一个新的序列来扩展当前序列 (它会将该序列的中元素添加到列表中) 参数需要传递 |
pop() | 根据索引删除并返回指定元素 |
remove() | 删除指定元素 (如果相同值的元素有多个,只会删除第一个) |
reverse() | 翻转列表 |
sort(key=None,reverse=False) | 用来对列表中的元素进行排序 reverse:True反序;False 正序 |
6.2 实际运用
6.2.1、添加方法
- append()
# list.append() 向类表中最后的位置插入一个元素 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.append('凯') print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬', '凯']
- insert(arg1,arg2)
# list.insert() 向列表中的指定位置插入一个元素,第一个参数是要插入的位置,第二个参数是要插入的内容 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.insert(4, '亚瑟') print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '亚瑟', '安琪拉', '虞姬']
- extend(iterable)
# list.extend() 使用新的序列来扩展当前序列,就是添加多个元素 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.extend(['亚瑟', '凯']) print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬', '亚瑟', '凯']
6.2.2、删除方法
- pop()
# list.pop() 根据索引删除并返回元素, 如果不传递索引,默认删除最后一个 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a = a.pop() print(a) 运行结果 》》》虞姬
- remove()
# list.remove() 删除指定的元素 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.remove('鲁班') print(a) 运行结果 》》》['孙悟空', '猪八戒', '露娜', '安琪拉', '虞姬']
6.2.4、反转列表
- reverse()
a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.reverse() print(a) 运行结果 》》》['虞姬', '安琪拉', '露娜', '鲁班', '猪八戒', '孙悟空']
6.2.1、排序
- sort(key=None,reverse=False)
# list.sort() 默认是正序排序 他有一个参数reverse a = [4,5,2,7,1,0,5,8] a.sort(reverse=True) print(a) 运行结果 》》》[8, 7, 5, 5, 4, 2, 1, 0]
7、对条件语句的补充(for循环)
7.1、基本概念
for 语句是 Python 中执行迭代的两个语句之一,另一个语句是 while。while在之前的博客里有讲过,这里我们补充介绍一下for循环的用法。
Python 中,for 循环用于遍历一个迭代对象的所有元素。循环内的语句段会针对迭代对象的每一个元素项目都执行一次。这里我们用的迭代对象就是列表和range。
7.2、for 循环语法
- 字符串
for i(迭代变量) in 'Python': 循环体
- range
for i(迭代变量) in range(1,9): 循环体
- 序列
for i(迭代变量) in 序列(遍历的规则): 循环体
7.2 range的用法
- for 迭代变量 in range ( i, j [,k ]):
参数说明:
这个也是左闭右开区间,所以终止值不可取
i: 初始值(默认为‘0’)
j: 终止值(默认为‘1’)
k: 步长值,即每次重复操作时比上一次操作所增长的数值。(默认为‘1’)
执行过程:
第一步:将 i 值传递给 ‘迭代变量’,然后执行一次内部语句;
第二步:在 i 的基础上 + k 再次传递给 ‘迭代变量’,如果 ‘迭代变量’ 的值小于 ‘j’ 的值,则再次执行内部语句,否则退出for循环。
详情如下:
for i in range(9): print(i)
运行结果如图;
8、课后作业
8.1、 现在有 a = [1,2,3,4,5,6] 用多种方式实现列表的反转([6,5,4,3,2,1]) 并写出推导过程
# 第一种方法,使用append a = [1,2,3,4,5,6] b = [] for i in a: b.append(a[6-i]) print(b) # 第二种方法,切片的运用 a = [1,2,3,4,5,6] print(a[::-1]) # 第三种方法,反转列表 a = [1,2,3,4,5,6] a.reverse() print(a) # 第四种方法,排序 a = [1,2,3,4,5,6] a.sort(reverse=True) print(a)
运行结果如下:
知识点运用及编写思路:
第一种方法用到了列表方法append和for循环的配合,每一次运行都将列表a中的值添加给b,达到逆序的效果。
第二种方法是切片的逆序打印,详情可以看上面切片的介绍及运用。
第三种和第四张方法都是列表方法的运用,不过第三种不管里面的元素是什么类型的都可以逆序打印,但第四张只能针对像这种原本就是元素从小到大的列表,其他的就达不到逆序的效果。
8.2、给用户9次机会 猜1 - 10 个数字随机来猜数字。
# 第一种 list1 = [1,2,3,4,5,6,7,8,9,10] list2=[] print('现在我们来猜数字,给你9次机会哦') for i in range(1,10): a = int(input('请输入1 - 10中的数字:')) if a in list1: print(f'你猜错啦,不是{a}') list2.append(a) else: print('哎呀,要猜1到10内的数字哦!!!') continue else: for a in list1: if a not in list2: d = a print(f'哈哈哈,你9次都没猜对哦!!!应该是{d}才对哦!') # 第二种 list1 = [1,2,3,4,5,6,7,8,9,10] list2=[] print('现在我们来猜数字,给你9次机会哦') i=1 while i
- 运行结果如下(最终方法的运行)
- 知识点运用及编写思路:
这3种方法也是循序渐进的,由
Cheney老师以及群里的各位大佬
指点改进的
第一种方法中规中矩,就是利用for循环,循环9次,让用户每次都猜一次,我们就将用户猜的值添加给列表list2,最后9次循环之后将list1与list2的值进行判断,最后输出用户没有猜到的值。
第二种方法就是再第一题的基础上加上了判断,限定用户必须猜1~10之间的数字。
上述的2种方法也能达到效果,但是还是不够简便,所以在听取了群里的大佬西安聂泽雨
的意见后改的,使用remove方法将用户猜的数字都从列表中删除,这样就能达到与上面2种方法相同的效果,也简化了代码。
在此,还要非常感谢一下Cheney老师以及群里的大佬的指点与帮助,让我学习到了更多的代码知识以及思路。学无止境,希望各位再观看完我的博客后,能给我的不足地方指出,谢谢。
- 下面是我原本写的,解题思路稍微有点偏差,也可以借鉴一下的
- 让用户9次都猜不对,前2种方法都有一点点问题,可以结合第三种一起理解一下
# 让用户9次都猜不对,然后每一次都输出一个值 # 第一种方法 list1 = [1,2,3,4,5,6,7,8,9,10] for i in range(1,10): a = int(input('请输入1 - 10中的数字:')) b = list1[a+1] print(f'你猜错啦,应该是{b}才对哦!') else: print('哈哈哈,你9次都没猜对哦!!!') # 第二种方法 list1 = [1,2,3,4,5,6,7,8,9,10] i=1 while i=1 and a
运行结果如下(这里只展示第3种方法的效果,还有2种也差不多):
知识点运用及编写思路:
此代码是我在理解错题目意思后写的,让用户9次都猜不对,每一次都输出一个数字。
这里我写了3种方法,思路是循序渐进的,应该更好理解。
首先我们第一种方法
用到的就是for循环和列表的运用,先创建一个列表,里面的元素就是1~10的数字,然后不管用户输入什么数字,我这边都加上2输出,这里因为索引是从0开始,所以list1[a+1]就能达到这种效果,但是我发现这个方法又不足,先不说,我们输出的数字不随机,再有就是我不管输入什么数字都行,缺少了一个判断,所以我又进行了更改
第二种方法
我就在第一种方法加上了if判断,但是我这个时候又遇到一个问题,如果接着用for循环,就算我输不是1 ~ 10 内的数字,然后他总的循环只能有9次,所以不符合我的预期效果,这个时候我想到了while循环,并将其添加进去,这时我就限定了用户只能输入1 ~ 10内的数字。
第三种方法
,是我想让我们输出的数字也随机,这是我想到了random模块,使用这个模块不就能随机了能生成随机数了嘛,但是我又想到这个还有一个问题,就是他有很大概率让用户懵中,所以我这又给他加了个循环,使其就算猜中了也没用,猜中我就换一个随机数就好了。最后的效果就如上图了。
8.3、有两个列表 lst1 = [11, 22, 33] lst2 = [22, 33, 44]获取内容相同的元素
# 第一种方法 while循环 lst1 = [11, 22, 33] lst2 = [22, 33, 44] a = 0 c = '相同的元素为:' while a
- 运行结果如下:
- 知识点运用及编写思路:
这题比较容易,获取2个列表相同的元素,我们只要用一下循环嵌套就好了,外循环和内循环都是循环3次,外循环就是lst1的元素数量,内循环是lst2的元素数量,之后那list1的每一个元素都与list2的元素一一对比判断就行了,相同的复制给c,最后直接输出c即可。
8.4、现在有8位老师,3个办公室,要求将8位老师随机的分配到三个办公室中
# 第一种方法 while循环 import random a = 1 while a
运行结果如下:
知识点运用及编写思路:
这题说白了就是random模块与循环之间的使用,将老师的数量作为迭代变量,也就是循环的次数,然后使用random模块生产随机的1~3之间的数字,然后就是输出啦。
9、附加(个人代码练习)
9.1、求1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100的值
# 求1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100的值 # while循环 i=1 sum=0 while i<blockquote><p>运行结果:<br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/052/035db9fe0baa39f789db2df222f2d9f8-10.png" class="lazy" alt="Detailed explanation of python lists"></p></blockquote><p><strong>9.2、计算下面数列的和值。 1/3+3/5+5/7+…+97/99</strong></p><pre class="brush:php;toolbar:false"># 计算下面数列的和值。 1/3+3/5+5/7+....+97/99 # while循环 i,j,sum = 1,3,0 while i<blockquote><p>运行结果:<br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/052/035db9fe0baa39f789db2df222f2d9f8-11.png" class="lazy" alt="Detailed explanation of python lists"></p></blockquote><p><strong>9.3、 输入2个数值,判断之间有多少个素数,并输出所有素数</strong></p><pre class="brush:php;toolbar:false"># 输入2个数值,判断之间有多少个素数,并输出所有素数 c=[int(input('输入第一个数:')),int(input('输入第二个数:'))] c.sort(reverse=False) #保证2个数以升序方式排列 a,b=c[0],c[1] while a <blockquote><p>运行结果:<br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/052/035db9fe0baa39f789db2df222f2d9f8-12.png" class="lazy" alt="Detailed explanation of python lists"></p></blockquote><blockquote><p><strong>相关免费学习推荐:</strong><a href="https://www.php.cn/course/list/30.html" target="_blank"><strong>python教程</strong></a><strong>(视频)</strong></p></blockquote>
The above is the detailed content of Detailed explanation of python lists. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap
