Home>Article>Backend Development> An article to help you learn Python lists

An article to help you learn Python lists

不言
不言 forward
2018-11-27 16:00:47 1810browse

The content of this article is about an article to help you learn Python lists. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A thousand miles begins with a single step. To develop a pair of eyes that can see everything, you must first learn the basic skills in a down-to-earth manner. Today, I will take you to review the Python list carefully. You can learn something new by reviewing the past, that’s why.

Of course, you should also think divergently while reviewing, because some seemingly insignificant and conventional language habits, such as why array indexes start from 0, may have a lot of history behind them. To know what is happening, you also need to know why it is happening. Meow meow meow~~~

Finally, on top of the basic knowledge, you should also explore advanced ones, such as learning generator expressions, so that you can have a more solid grasp. Basics, and can be integrated to achieve a more comprehensive cognitive upgrade.

What is the list in Python?

A list is an ordered collection that can add, find, and delete elements at any time.

List supports adding elements of different data types: numbers, strings, lists, tuples, etc.

The list can traverse all elements through ordered indexes. Counting from front to back, the index is [0, n-1]. Counting from back to front, the index is [-1, -n], where n is the length of the list.

The list can be an empty list without elements, or it can contain too many elements (if the memory size supports it).

list_a = [] # 空列表,即len(list_a) == 0 list_b = [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] # list_b 长度为5,包含2个数字元素、1个字符串元素、1个列表元素和1个元组元素 len(list_b) == 5 list_b[0] == list_b[-5] == 2018 lits_b[3] == list_b[-2] == ['hi', 1, 2] lits_b[4] == list_b[-1] == (33, 44)

How to operate lists in Python?

1) Create a list:

Wrap the elements in square brackets [], and separate the elements with commas.

Use the list() method to convert and generate a list.

List generation/list analysis/list comprehension, generate a list.

list_a = [1, 2, 3] list_b = list("abc") # list_b == ['a', 'b', 'c'] list_c = list((4, 5, 6)) # list_c == [4, 5, 6] list_d = [i for i in list_a] # list_d == [1, 2, 3] list_e = [i*j for i in list_a for j in list_c] # list_e == [4,5,6,10,12,12,15,18] list_f = [i*j for i,j in zip(list_a,list_c)] # list_f == [4, 10, 18] list_g = [i for i in list_a if i%2 == 0] # list_g == [2] # 结合range()函数,range(start, stop[, step]) list_h = list(range(3)) # list_h == [0, 1, 2] list_i = list(range(3,7)) # list_i == [3, 4, 5, 6] list_j = list(range(3,9,2)) # list_j == [3, 5, 7] # 找出100以内的能够被3整除的正整数 list_k = list(range(3,100,3)) # list_k == [3, 6, 9, ..., 96, 99]

2) Expand the list:

Use the append() method to add a single new element to the end of the list.

Use the insert() method to add an element at a specified position in the list.

Use the " " operator to splice the two lists into a new list.

Use the extend() method to splice one list into another list.

# 以下分别添加2个元素 list_a = [] list_a.append('happy') # list_a == ['happy'] list_a.insert(0, 'very') # list_a == ['very', 'happy'] # 以下两种扩充列表方式 list_1 = ['I', 'am'] list_2 = ['very', 'happy'] list_3 = list_1 + list_2 # 新列表 list_3 == ['I', 'am', 'very', 'happy'] list_1.extend(list_2) # 原列表1扩充,list_1 == ['I', 'am', 'very', 'happy']

3) Delete the list and destroy the list:

Use the del list[m] statement to delete the element at the specified index m.

Use the remove() method to delete the element with the specified value (the first matching item).

Use the pop() method to take out and delete a single element at the end of the list.

Use the pop(m) method to remove and delete the element with index value m.

Use the clear() method to clear the elements of the list. (The cup is still there, but the water is empty)

Use the del list statement to destroy the entire list. (Both cups and water are gone)

# 以下4种删除列表元素方式 list_1 = list_2 = list_3 = list_4 = ['I', 'am', 'very', 'happy'] del list_1[0] # list_1 == ['am', 'very', 'happy'] list_2.remove('I') # list_2 == ['am', 'very', 'happy'] list_3.pop() # list_3 == ['I', 'am', 'very'] list_4.pop(0) # list_4 == ['am', 'very', 'happy'] # 清空与销毁 list_a = [1, 2, 3] list_b = [1, 2, 3] list_b.clear() # list_b == [] del list_a # 没有list_a了,再使用则会报错

4) List slicing:

Basic meaning:Start from the i-th position, go to the right after Up to n elements, filter by m intervals

Basic format: [i : i n : m]; i is the starting index value of the slice, which can be omitted when it is the first of the list; i n is the end of the slice The position can be omitted when it is the last position in the list; m does not need to be provided. The default value is 1 and 0 is not allowed. When m is a negative number, the list is flipped. Note: These values can be larger than the list length and will not be reported as out of bounds.

li = [1, 4, 5, 6, 7, 9, 11, 14, 16] # 以下写法都可以表示整个列表,其中 X >= len(li) li[0:X] == li[0:] == li[:X] == li[:] == li[::] == li[-X:X] == li[-X:] li[1:5] == [4,5,6,7] # 从1起,取5-1位元素 li[1:5:2] == [4,6] # 从1起,取5-1位元素,按2间隔过滤 li[-1:] == [16] # 取倒数第一个元素 li[-4:-2] == [9, 11] # 从倒数第四起,取-2-(-4)=2位元素 li[:-2] == li[-len(li):-2] == [1,4,5,6,7,9,11] # 从头开始,取-2-(-len(li))=7位元素 # 注意列表先翻转,再截取 li[::-1] == [16,14,11,9,7,6,5,4,1] # 翻转整个列表 li[::-2] == [16,11,7,5,1] # 翻转整个列表,再按2间隔过滤 li[:-5:-1] == [16,14,11,9] # 翻转整个列表,取-5-(-len(li))=4位元素 li[:-5:-3] == [16,9] # 翻转整个列表,取-5-(-len(li))=4位元素,再按3间隔过滤 li[::0] # 报错(ValueError: slice step cannot be zero)

5) Other operations:

Use the len() method to count the number of all elements.

Use the count() method to count the number of elements with a specified value.

Use the max() method to count the maximum value in the element (the element types are required to be the same; numerical types are directly compared, and other types are compared to IDs)

Use the min() method to count the maximum value in the element Minimum value (the element types are required to be the same; numeric types are directly compared, other types are compared with IDs)

Use the index() method to find the index position of the element with the specified value (the first match).

Use the reverse() method to flip the elements in the list.

Use the copy() method to shallowly copy and generate a new list.

Use the deepcopy() method to deep copy and generate a new list.

Use the sort() method to sort based on the original list.

Use the sorted() method to sort the elements of the original list based on the new list.

list_1 = [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] len(list_1) == 5 list_1.count(10) == 1 # 元素10的数量为1 list_1.index(10) == 1 # 元素10的索引为1 list_1.reverse() # list_1 == [(33, 44), ['hi', 1, 2], '2018-10-1', 10, 2018] # 比较浅拷贝与深拷贝 import copy list_a = [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] list_b = ['hi', 1, 2] list_c = list_a.copy() # list_c == [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] list_d = copy.deepcopy(list_a) # list_d == [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] # 改变原列表中的可变对象元素 list_a[3].append('new') # list_a == [2018, 10, '2018-10-1', ['hi', 1, 2, 'new'], (33, 44)] # 浅拷贝中的可变对象会随原列表变化而变化 list_c == [2018, 10, '2018-10-1', ['hi', 1, 2, 'new'], (33, 44)] # 深拷贝中的可变对象不会随原列表变化而变化 list_d == [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] # 比较sort() 与 sorted() list_1 = list_2 = [2,1,4,6,5,3] list_1.sort() # 原列表变化:list_1 == [1,2,3,4,5,6] list_3 = sorted(list_2) # 原列表不变:list_2 == [2,1,4,6,5,3]; list_3 == [1,2,3,4,5,6]

Why does Python list index start from 0?

The authoritative explanation comes from the blog post of Guido van Rossum (the father of Python): "Why Python uses 0-based indexing"

Summary in one sentence: Indexing starts from 0, and slicing usage is very simple grace.

The translation essence is as follows:

One of the reasons why I decided to use 0-based indexing in Python is the slice notation.

Let’s take a look at how to use slices first. Perhaps the most common usage is to "take the first n elements" or "index from the i-th position and take the last n elements" (the former usage is actually a special usage of i==starting position). It would be very elegant if these two usages could be implemented without ugly 1 or -1 in the expression.

If you use 0-based indexing, half-open interval slicing and default matching intervals (Python finally adopts this method), the slicing syntax for the above two situations becomes very beautiful: a[:n ] and a[i:i n], the former is the abbreviation of a[0:n].

如果使用1-based的索引方式,那么,想让a[:n]表达“取前n个元素”的意思,你要么使用闭合区间切片语法,要么在切片语法中使用切片起始位和切片长度作为切片参数。半开区间切片语法如果和1-based的索引方式结合起来,则会变得不优雅。而使用闭合区间切片语法的话,为了从第i位索引开始取后n个元素,你就得把表达式写成a[i:i+n-1]。

……

特别是当两个切片操作位置邻接时,第一个切片操作的终点索引值是第二个切片的起点索引值时,太漂亮了,无法舍弃。例如,你想将一个字符串以i,j两个位置切成三部分,这三部分的表达式将会是a[:i],a[i:j]和a[j:]。

其它编程语言的索引?

索引从0开始的编程语言:C、C++、Python、Java、PHP、Ruby、Javascript...

索引从1开始的编程语言:ABC、Matlab、VB、易语言、大部分shell语言...

索引从其它值开始的编程语言:Pascal、Lua...

还有像表示星期、月份等序列结构的数据,各种编程语言也划分成了不同阵营。

它们出于何种考虑?

C语言:索引从0开始,可以大大提升内存寻址计算的效率,详细分析参考《C语言数组元素下标为何从0开始》

大部分shell语言:大多数是从1开始,来源参考stackexchange这篇问答

Pascal、Lua:默认从1开始,但支持改变起始索引值,原因据说是对非专业的开发者更友好,来源参考这篇知乎问答

以上列举的原因是最审慎的、体面的解释,话题应该到此终结,因为“索引应该从几开始最好”这个问题的破坏性不亚于“哪种编程语言是最好的”......

优雅漂亮的结尾:生成器表达式

列表生成式是一种漂亮优雅的东西,然而它有一个致命的缺点:它一次性把所有元素加载到内存中,当列表过长的时候,便会占据过多的内存资源,而且,我们通常仅需要使用少数的元素,这样未使用的元素所占据的绝大部分的内存,就成了不必要的支出。

生成器是一种更高级更优雅的东西,它使用“懒加载”的原理,并不生成完整的列表,而是迭代地、即时地、按需地生成元素,这样不仅能极大地节省内存空间,而且,在理论上,它可以生成一个无穷大的列表!

大多数生成器是以函数来实现的,然而,它并不返回(return)一个值,而是生成(yield)一个值,并挂起程序。然后,通过next()方法生成并马上返回一个元素,或者通过for循环,逐一生成和返回全部元素。

next()效率太低,且调用次数越界时会抛出StopIteration的异常,而for循环会自动捕捉这个异常,并停止调用,所以使用更佳。

# 计算斐波那契数列的生成器 def fibon(n): a = b = 1 for i in range(n): yield a # 使用yield a, b = b, a + b # 计算前1000000个数,通过next()函数,按顺序每次生成一个数 g = fibon(1000000) next(g) # 1 next(g) # 1 next(g) # 2 next(g) # 3 next(g) # 5 # 以此类推,但若调用超过1000000次,就会报异常StopIteration # 计算前1000000个数,通过for循环逐一打印生成数 for x in fibon(1000000): print(x)

生成器表达式与列表生成式极其形似,只是把[]改成了(),但背后的原理大不相同。

l = [x*2 for x in range(5)] # 列表生成式,4以内整数的2倍数 g = (x*2 for x in range(5)) # 生成器表达式 type(l) # 结果: type(g) # 结果: print(l) # 结果:[0,2,4,6,8] print(g) # 结果: next(g) # 0 next(g) # 2 next(g) # 4 next(g) # 6 next(g) # 8 next(g) # Traceback (most recent call last): ....StopIteration for x in g: print(x, end=' ') # 结果:0 2 4 6 8

The above is the detailed content of An article to help you learn Python lists. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete