Detailed explanation of python lists

coldplay.xixi
Release: 2021-01-29 17:56:06
forward
3770 people have browsed it

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. Additional (Personal Code Practice)
  • 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

The index of the sequence is actually in the ## of the previous fourth blog #String Slicing
I mentioned it before, but I’ll mention it again because it’s very

important, important, important, 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

1.1. Basic concepts

Sequence is the most basic data structure in Python.

  •  Sequence is used to save
a set of ordered data
. 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 added

The sequence isa data structure called a container. Sequences (for example: lists, tuples) and maps (for example: dictionaries).
Each element in the sequence has a number, whileeach 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.

Data structure refers to the way data is stored in the computer
  • 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 array
a=['a','b','c','d','e','f','g','h ','i']


1.3. Practical application

  • The following is an array to obtain the elements of a single array through indexing.
a=['a','b','c','d','e','f','g','h','i'] print(a[0]) # 运行结果 》》》a print(a[4]) # 运行结果 》》》e print(a[8]) # 运行结果 》》》i print(a[-1]) # 运行结果 》》》i
Copy after login

2. List(list)

2.1. The concept of list

The list is An object in Python
The role of a list:

  • A list can save multiple ordered data
  • A list is an object used to store objects

 A list is composed of a series of elements arranged in a specific order, usually containing multiple elements,For example: string, integer value, floating point value, list, None, list, dictionary, etc.. In python, use square brackets [ ] to represent a list, and use commas to separate the elements

2.2. Use of lists

  • Creation of lists : Create an empty list through []
a=[] print(a) # 运行结果 》》》[]
Copy after login
  • Creation of list: direct assignment
a=['a','b','c','d','e','f','g','h','i'] print(a) # 运行结果 》》》['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Copy after login

3, slicing

3.1. The concept of slicing

  In the fourth lecture on slicing strings, we talked about the use of string slicing. In fact, slicing can be used for more than just strings. , lists, and tuples can all use slicing.
  Slicing is done by taking out the desired part of the known data. Slicing is based on iterable objects, taking out elements of any length, and the range and frequency can also be customized.
Summary: Slicing is a fetching operation that does not change the original value

  • Slicing refers to obtaining a sublist from an existingiterable object (list)
  • Obtaining the specified element through slicing

3.2. Syntax

  • List [Start: End: Step] The left-closed right-open interval takes the head but does not take the tail. The default step size is 1

To put it in detail:
1. Left-closed and right-open interval:When obtaining elements through slicing, the element at the starting position will be included, not Elements including the end position
2. The indexes of the start position and the end position do not need to be written

  • If the end position is omitted, it will be intercepted from the current start position to the end
  • If the start position is omitted, the elements from the first element to the end will be intercepted, but the end element will not be included.
  • If the start position and the end position are both omitted, then the elements from the first element to the end will be intercepted. Start intercepting elements to the last element

3. The step size indicates the interval for obtaining elements each time. The default is 1 (can be omitted)
4. The step size cannot be 0, but It can be a negative number

3.3. Practical application

  • Personal experience on slicing learning: It is recommended to type it several times by yourself and read more concepts. In the end, it is not as effective as practicing it several times.
a=['a','b','c','d','e','f','g','h','i'] print(a[::]) # 运行结果 》》》['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] # 运行讲解:起始位置、结束位置和步长都是空,既打印所有列表元素 print(a[0:3]) # 默认步长为1 # 运行结果 》》》['a', 'b', 'c'] # 运行讲解:a列表从第一位a取到第4位d,d不可取,所以只能取到c,既abc这3个元素 # 也可以是如下写法,从 0 开始就可以把初始位置省略,效果如上 print(a[:3]) print(a[0:4:2]) # 初始位置为0可省略 # 运行结果 》》》['a', 'c'] # 运行讲解:a列表从第一位a取到第5位e,e不可取,步长为2,只能取到ac print(a[-1:-4]) # 运行结果 》》》[] # 运行讲解:步长不写默认为1,但初始和结束位置为负,但初始大于结束位置,则什么值都取不到 print(a[-4:-1:1]) # 运行结果 》》》['f', 'g', 'h'] # 运行讲解:初始小于结束位置,从倒数第4位f取到最后1位i,i不可取,步长为1 print(a[-1:-4:-1]) # 运行结果 》》》['i', 'h', 'g'] # 运行讲解:从倒数第一位i取到倒数第4位e(e不可取)。 print(a[::-1]) # 运行结果 》》》['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] # 运行讲解:初始和结束位置都为空,步长为负,则逆序打印
Copy after login

4. Common operations

4.1 Operation and instructions

list 'a' 'b' 'c' 'd' 'e' 'f 'g' 'h' 'i' Number (positive sequence) 0 1 2 3 4 5 6 7 8 Number (reverse order) -9 -8 -7 -6 -5 -4 -3 -2 -1

4.2 实际运用

  • +的使用
a = [1, 2, 3] + [4, 5, 6] print(a) # 运行结果 》》》[1, 2, 3, 4, 5, 6]
Copy after login
  • *的使用
a = [1, 2, 3] *3 print(a) # 运行结果 》》》[1, 2, 3, 1, 2, 3, 1, 2, 3] # 错误用法:列表乘列表,不用这样使用 a = [1, 2, 3] * [4, 5, 6] #上面这种写法会报错的哦,像这样: # TypeError: can't multiply sequence by non-int of type 'list' # 类型错误:不能用“列表”类型的非整数乘序列
Copy after login
  • in的使用
a = ['p','y','t','h','o','n'] print('y' in a) # 运行结果 》》》True
Copy after login
  • not in的使用
a = ['p','y','t','h','o','n'] print('y' not in a) # 运行结果 》》》 False
Copy after login
  • len() 的使用
a = ['p','y','t','h','o','n'] print(len(a)) # 运行结果 》》》6
Copy after login
  • max()的使用
b = [1, 2, 3, 1] print(max(b)) # 运行结果 》》》3
Copy after login
  • min()的使用
b = [1, 2, 3, 1] print(min(b)) # 运行结果 》》》1
Copy after login
  • list.index的使用
a = ['p','y','t','h','o','n'] print(a.index('y')) # 运行结果 》》》1 # 返回的结果就是当前这个数据‘y’的索引
Copy after login

注:列表没有find用法,使用find会报错的

  • list.count(x)
a = ['p','y','t','h','o','n','y'] print(a.count('y')) # 运行结果 》》》2 # 查找有几个这种元素
Copy after login
  • list.copy(x)
a = ['p','y','t','h','o','n'] print(a.copy()) # 运行结果 》》》['p', 'y', 't', 'h', 'o', 'n']
Copy after login
  • cmp(list1, list2),这里用operator模块
# cmp是python2中的函数,python3中以无法使用,可以用operator代替,效果一样的 a = ['11','22','33'] b = ['22','33','44'] import operator print(operator.eq(a,b)) # 运行结果 》》》False
Copy after login

这里有一种关于operator模块的使用,感兴趣的朋友可以了解一下
Detailed explanation of python lists

5、修改列表

通过切片来修改(起始就是给切片的内容重新赋值,但是赋值的内容必须是一个序列)
当设置了步长时,序列中元素的个数必须和切片中元素的个数保持一致
通过切片来删除元素

  • del list[起始 : 结束]
    list = []

5.1、 直接修改

a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a[-1] = '亚瑟' print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '亚瑟']
Copy after login

5.2、切片修改

a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] print(a[3:5]) # 运行结果 》》》['露娜', '安琪拉'] a[3:4] = '橘右京' print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '橘', '右', '京', '安琪拉', '虞姬'] a[3:5] = '李白' print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '李', '白', '京', '安琪拉', '虞姬'] a[0:0] = ['牛魔'] print(a) # 运行结果 》》》['牛魔', '孙悟空', '猪八戒', '鲁班', '李', '白', '京', '安琪拉', '虞姬'] a[::2] = ['凯','凯','凯','凯','凯'] print(a) # 运行结果 》》》['凯', '孙悟空', '凯', '鲁班', '凯', '白', '凯', '安琪拉', '凯'] # 取到多少个数据,替换的数据就得有多少 print(a) print(a.index('安琪拉')) # 运行结果 》》》7
Copy after login

5.3、 删除 关键字

a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] del a[-1] # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉']
Copy after login

6、列表的方法

6.1 方法与说明

##list.index(x[, start[, end]] ) The first parameter gets the position of the specified element in the list list.count(x) Count the number of times the specified element appears in the list list.copy(x) Shallow copy list cmp(list1, list2) Compare the elements of two lists
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 second parameter indicates the starting position of the search
The third parameter indicates the end position of the search
operator module
方法 说明
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) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬', '凯']
Copy after login
  • insert(arg1,arg2)
# list.insert() 向列表中的指定位置插入一个元素,第一个参数是要插入的位置,第二个参数是要插入的内容 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.insert(4, '亚瑟') print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '亚瑟', '安琪拉', '虞姬']
Copy after login
  • extend(iterable)
# list.extend() 使用新的序列来扩展当前序列,就是添加多个元素 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.extend(['亚瑟', '凯']) print(a) # 运行结果 》》》['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬', '亚瑟', '凯']
Copy after login

6.2.2、删除方法

  • pop()
# list.pop() 根据索引删除并返回元素, 如果不传递索引,默认删除最后一个 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a = a.pop() print(a) 运行结果 》》》虞姬
Copy after login
  • remove()
# list.remove() 删除指定的元素 a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.remove('鲁班') print(a) 运行结果 》》》['孙悟空', '猪八戒', '露娜', '安琪拉', '虞姬']
Copy after login

6.2.4、反转列表

  • reverse()
a = ['孙悟空', '猪八戒', '鲁班', '露娜', '安琪拉', '虞姬'] a.reverse() print(a) 运行结果 》》》['虞姬', '安琪拉', '露娜', '鲁班', '猪八戒', '孙悟空']
Copy after login

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]
Copy after login

7、对条件语句的补充(for循环)

7.1、基本概念

  for 语句是 Python 中执行迭代的两个语句之一,另一个语句是 while。while在之前的博客里有讲过,这里我们补充介绍一下for循环的用法。
  Python 中,for 循环用于遍历一个迭代对象的所有元素。循环内的语句段会针对迭代对象的每一个元素项目都执行一次。这里我们用的迭代对象就是列表和range。

7.2、for 循环语法

  • 字符串
for i(迭代变量) in 'Python': 循环体
Copy after login
  • range
for i(迭代变量) in range(1,9): 循环体
Copy after login
  • 序列
for i(迭代变量) in 序列(遍历的规则): 循环体
Copy after login

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)
Copy after login

运行结果如图;
Detailed explanation of python lists

8、课后作业

Detailed explanation of python lists

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)
Copy after login
  • 运行结果如下:
    Detailed explanation of python lists

  • 知识点运用及编写思路:

  第一种方法用到了列表方法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
Copy after login
  • 运行结果如下(最终方法的运行)

Detailed explanation of python lists

  • 知识点运用及编写思路:

  这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
Copy after login
  • 运行结果如下(这里只展示第3种方法的效果,还有2种也差不多):
    Detailed explanation of python lists

  • 知识点运用及编写思路:

  此代码是我在理解错题目意思后写的,让用户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
Copy after login
  • 运行结果如下:
    Detailed explanation of python lists
  • 知识点运用及编写思路:

  这题比较容易,获取2个列表相同的元素,我们只要用一下循环嵌套就好了,外循环和内循环都是循环3次,外循环就是lst1的元素数量,内循环是lst2的元素数量,之后那list1的每一个元素都与list2的元素一一对比判断就行了,相同的复制给c,最后直接输出c即可。

8.4、现在有8位老师,3个办公室,要求将8位老师随机的分配到三个办公室中

# 第一种方法 while循环 import random a = 1 while a
Copy after login
  • 运行结果如下:
    Detailed explanation of python lists

  • 知识点运用及编写思路:

  这题说白了就是random模块与循环之间的使用,将老师的数量作为迭代变量,也就是循环的次数,然后使用random模块生产随机的1~3之间的数字,然后就是输出啦。

Detailed explanation of python lists

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

运行结果:
Detailed explanation of python lists

9.2、计算下面数列的和值。 1/3+3/5+5/7+…+97/99

# 计算下面数列的和值。 1/3+3/5+5/7+....+97/99 # while循环 i,j,sum = 1,3,0 while i

运行结果:
Detailed explanation of python lists

9.3、 输入2个数值,判断之间有多少个素数,并输出所有素数

# 输入2个数值,判断之间有多少个素数,并输出所有素数 c=[int(input('输入第一个数:')),int(input('输入第二个数:'))] c.sort(reverse=False) #保证2个数以升序方式排列 a,b=c[0],c[1] while a 

运行结果:
Detailed explanation of python lists

相关免费学习推荐:python教程(视频)

Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!