python3中的常见知识点2
python3中的常见知识点2
- 列表与栈和队列
- map()函数
- python列表遍历的4种方式
- 参考链接
列表栈和队列
1、列表作为栈使用
栈:先进后出,First In Last Out
使用 append()添加项到栈顶,使用无参的 pop() 从栈顶减出项。
2、列表作为队列使用
队列:先进先出,First In first Out
deque模块可以快速地从两端实现队列操作。
map()函数
map() 会根据提供的函数对指定序列做映射。
map()语法,function为函数,iterable为一个或多个序列。
map(function, iterable, ...)
例子:
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
注意:
Python 2.x 返回列表。
Python 3.x 返回迭代器。
python列表遍历的4种方式
方法1 直接利用for循环遍历
L = ['one', 'two', 'three', 'four']
for i in L:
print(i)
输出:
one
two
three
four
方法2 利用range()
range()函数语法,start为计数起始点,默认0;stop为计数终点(不包括stop);step为步长,默认为1。
range(start, stop[, step])
例子
L = ['one', 'two', 'three', 'four']
for i in range(len(L)):
print(i, L[i])
输出:
0 one
1 two
2 three
3 four
方法3 利用enumerate()函数
enumerate()函数语法,sequence为一个序列、迭代器或其他支持迭代对象;start为下标起始位置。
enumerate(sequence, [start=0])
例子
L = ['one', 'two', 'three', 'four']
for index, value in enumerate(L):
print(index, value)
输出:
0 one
1 two
2 three
3 four
方法4 iter() 函数
iter() 函数用来生成迭代器。
iter() 函数语法,object 为支持迭代的集合对象。
iter(object[, sentinel])
例子
L = ['one', 'two', 'three', 'four']
for i in iter(L):
print(i)
输出:
one
two
three
four
参考链接
https://yiyibooks.cn/xx/python_352/tutorial/datastructures.html
http://www.runoob.com/python3/python3-tutorial.html
本文来自博客园,作者:风兮177,转载请注明原文链接:https://www.cnblogs.com/fengxi177/p/16939385.html