在线客服
扫描二维码
下载博学谷APP扫描二维码
关注博学谷微信公众号
在Python中,列表(Lists)是很常见的数据结构。今天我们要来在线学习列表的相关知识点,主要内容有列表常用操作方法、堆栈、队列、列表推导、列表内置推导以及del表达式。一起来看看吧~
1、列表常用操作方法
list.append(x)
list末尾追加元素 x,等价于 a[len(a):]=[x]
list.extend(iterable)
list末尾追加可迭代类型元素(如添加[1,2])等价于 a[len(a):]=iterable
list.insert(i,x)
list指定位置i添加元素x
list.remove(x)
list中删除元素
list.pop([i])
从指定位置[i]处删除元素,未指定位置时,默认从末尾元素删除。
list.clear()
清空list数据
list.index(x[, start[, end]])
返回x在list中首次出现的位置, start,end 指定查找的范围。
list.count(x)
返回x在list中的个数
list.sort(key=None, reverse=False)
对list进行排序
list.reverse()
list元素倒序
list.copy()
返回list的复制数据,等价于a[:]
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
2、列表作为堆栈
堆栈的原则是数据 先进后出
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
3、列表作为队列
队列的原则是数据 先进先出
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
4、列表推导
根据List提供的相关方法,我们可以自己根据需求创建list
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
也可以使用lambda表达式来创建
squares = list(map(lambda x: x**2, range(10)))
或者更直接
squares = [x**2 for x in range(10)]
使用多个for循环或者if 组合语句也可以创建list
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y][(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
等价于
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
如果表达式为元组类型,使用时必须用 ()
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in <module>
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
lists推导也可以用混合表达式和内置函数
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
5、列表内置推导
下面是一个 3* 4的矩阵
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
下面方法可以将matrix数据转换为 4*3的矩阵。
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
等价于
>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
或者是这样
>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
上面操作完全可以使用list的内置函数 zip() 来实现
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
6、del表达式
使用可以直接删除List中的某个数值
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
也可以删除整个 list
>>> del a
Pyhton数据结构列表的学习内容就分享到这里了,相信大家对于Pyhton还有很多的疑惑,现在就在博学谷报名在线学习Python,就有名师一对一对你进行辅导。还等什么,现在就来体验吧~
— 申请免费试学名额 —
在职想转行提升,担心学不会?根据个人情况规划学习路线,闯关式自适应学习模式保证学习效果
讲师一对一辅导,在线答疑解惑,指导就业!
相关推荐 更多
Python在线培训班那个好?
Python是一个优势非常明显的编程语言,在人工智能、数据分析、爬虫、全栈开发、自动化测试、自动化运维等领域都有很大的作用。所以很多同学都加入Python学习的行列。对于没有时间参加线下培训的同学来讲,参加Python在线培训就更加方便了。那么Python在线培训班那个好?
8454
2019-08-08 11:56:39
Python入门基础练习题整理附答案
在初学者Python入门的时候,一方面要多注重积累理论基础知识,另一方面就是要多练手。因此本文整理了Python入门的基础练习题,相信对初学者会有很大的帮助。
13363
2019-08-14 18:15:39
Python中*args 和 **kwargs的用法总结
对于大部分Python新手来说,*args和**kwargs这两个魔法变量需要花大量的时间来解释。那么它们到底是什么呢?在什么时候使用它们呢?要搞清楚这些问题,首先你要明白,其实并不是必须写成*args和**kwargs。只有变量前面的*(星号)才是必须的。那下面就让我们先看看在Python中*args 和 **kwargs的用法总结吧。
6774
2020-06-19 16:36:08
应该怎么快速学习Python?
如今,Python 已然成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。然而,有一个问题始终摆在许多零基础学习者面前:应该怎么快速学习Python ?虽然Python 语法简单,被认为是最好学的编程语言,但是计算机小白想要学习,也有不小的难度。因此,最好的解决方式就是参加培训班,通过资深讲师的指导和专门为零基础学习者打造的课程,几个月就能上手Python 语言的开发。
5062
2020-07-09 15:29:20
拷贝文件夹cp和mv命令选项怎么使用?
拷贝文件夹cp和mv命令选项怎么使用?拷贝文件是我们办公文件中比较常用的命令,开发过程也需要掌握拷贝文件命令选项,今天我们就一起来学习一下。
3612
2022-03-08 11:40:55