在线客服
扫描二维码
下载博学谷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程序员使用频率比较高的5款开发工具推荐给大家。
7758
2019-07-09 10:23:01
为什么人工智能和Python要一起学?两者有何联系?
为什么人工智能和Python要一起学?两者有何联系?相信现在只要提到人工智能,就难免会带上Python,可以说Python就是人工智能的首选编程语言,由此人工智能已经和Python已经紧密联系在一起了。本文就和大家说说Python和人工智能不可分割的关系。
5752
2019-09-19 11:35:46
全套Python学习路线,快速上手
Python的初学者总希望能够得到一份Python学习路线图,小编经过多方面汇总,总结出比较全套Python学习路线,快速上手。
4513
2022-05-31 12:00:05
用Python编写第一个程序
如今,IT编程教育的市场趋势逐渐往泛互联网人群发展,这其中尤其是学习Python的人越来越多。本文要讲的就是怎么开始用Python编写第一个程序,开启你的学习之旅。首先在大家正式开始自己的编程之路之前,应该先把文本编辑器安装好,然后掌握命令行终端的运行方法。在一切准备就绪的时候,我们就可以开始第一个程序的编写了~
5626
2020-04-28 09:56:50
装饰器是什么?为什么要学习装饰器?
装饰器用于拓展原来函数功能的一种函数,在不改变原函数名或类名的情况下给函数增加新的功能。给已有函数增加额外功能的函数,它本质上就是一个闭包函数,我们学习得主要目的是掌握装饰器的语法格式。
3292
2021-12-06 11:11:22