Python容器总结

青春壹個敷衍的年華 提交于 2019-12-18 19:03:38

在Python的开发场景中, 我们主要使用了四种数据容器.
其详细介绍如下:

我们对其做了个比较
在这里插入图片描述
上诉四种类型, 又可以分成三类:
1、序列类型, 包括列表和元组.
在序列中循环时, 用enumerate()函数, 可以将索引位置与其对应的值同时取出.
代码如下.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

当同时在两个或者更多序列中循环市, 可以用zip(函数)将其内元素有序的一一匹配.
代码如下.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

循环3个

>>> _list1 = [1,2,3]
>>> _list2 = ['one','two','three']
>>> _list3 = ['h1','h2','h3']
>>> for x,y,z in zip(_list1,_list2,_list3):
...     print(x,y,z)
...
1 one h1
2 two h2
3 three h3

逆序循环一个序列, 使用reversed()函数.

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

顺序循环一个序列, 使用sorted()函数.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

当需要在循环的时候同时修改列表内容, 一般来说改为创建一个新列表是比较简单且安全的(因为修改列表涉及到索引的移动)

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

2、集合类型, 包括集合.
3、映射类型, 包括字典.

后补相同数据类型和不同数据类型的比较.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!