2.4.6 集合、 元组、 空值
作为同样需要网络工程师掌握的 Python 数据类型, 集合( Set)、元组( Tuple)、空值( None)相对来说使用频率不如字符串、整数、浮点数、列表、字典及布尔类型那么高,这里进行简单介绍。
1. 集合
集合是一种特殊的列表,里面没有重复的元素, 因为每个元素在集合中都只有一个,因此集合没有 count()方法。
集合可以通过大括号{}(与字典一样,但是集合没有键值对)或者函数 set()创建。
>>> interfaces = {‘Fa0/0’, 'Fa0/1', 'Fa0/2'}
>>> type(interfaces)
<class 'set'>
>>> vendors = set(['Cisco', 'Juniper', 'Arista', 'Cisco'])
>>> type(vendors)
<class 'set'>
>>> print (vendors)
{'Cisco', 'Arista', 'Juniper'}
>>>
vendors 列表中有两个重复的元素,即'Cisco',在用 set()函数将它转换成集合后,多余
的一个'Cisco'被去掉,只保留了一个。
集合是无序的,不能像列表那样使用索引号,也不具备 index()函数。
>>> vendors[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable
>>>
>>> vendors.index('Cisco')
Traceback (most recent call last):
File "<stdin>", line 1, in <mo