在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,就有名师一对一对你进行辅导。还等什么,现在就来体验吧~
— 申请免费试学名额 —
在职想转行提升,担心学不会?根据个人情况规划学习路线,闯关式自适应学习模式保证学习效果
讲师一对一辅导,在线答疑解惑,指导就业!
相关推荐 更多
MySQL和Redis高可用性体现在哪些方面?
MySQL和Redis高可用主要体现三个方面:MySQLReplication是MySQL官方提供的主从同步方案;Sentinel是Redis官方为集群提供的高可用解决方案;Sentinel主要功能。
4826
2019-07-16 17:00:32
好用的Python编辑器有哪些?Python编辑器推荐
好用的Python编辑器有哪些?Python编辑器推荐:Sublime Text、Sublime Text、Atom、PyCharm、Vim、clipse with PyDev、Emacs、Komodo Edit、Wing、PyScripter、The Eric Python IDE、Interactive Editor for Python等。
4454
2019-09-24 10:51:46
2019年Python学习路线及学习目标规划拿走不谢
2019年Python学习路线及学习目标规划拿走不谢,Python作为今年来特别受欢迎的编程语言,是AI时代头牌语言AI领域的敲门砖,Python已经入驻小学生教材,将来不学Python不仅知识会脱节与小朋友都没共同话题了,作为程序员的我们,必须给自己增加一项技能,提高职场竞争力,掌握一定的Python技能。
4681
2019-09-27 15:18:28
Python为什么这么火?编程零基础该如何学习Python?
Python为什么这么火?编程零基础该如何学习Python?其实Python的火爆不是偶然,时代的潮流驱动也好,自身的语言优势也好,对于零基础的学习者来说,学习Python都是最好的选择。至于Python学习方式有很多,看书、报培训班都是比较靠谱的,看大家适应哪种学习模式。
3023
2019-11-20 13:21:14
HTTP协议的作用是什么?怎么用?
HTTP协议的作用是什么?怎么用?HTTP协议超文本传输协议,传输HTTP 协议格式的数据是基于 TCP 传输协议的,发送数据之前需要先建立连接。
901
2021-12-17 16:17:58
热门文章
- 智能汽车用到哪些技术?
- 产品可行性分析需要考虑几个方面?
- 日常工作中程序员最讨厌哪些工作事项?
- 博学谷狂野大数据学习多长时间?
- IT互联网程序员的涨薪秘籍是什么?
- Java多线程遇到死锁三招彻底解决
- Python 开发人员经常遇哪些挑战?如何解决?
- 狂野架构师课程如何?能学到什么?
- 程序员面对996该如何应对?躺平还是卷起来?
- 2022年毕业生求职找工作青睐哪个行业? 查看更多
扫描二维码,了解更多信息
