python中的set(python基础学习)

一、定义

由一系列元素组成的无序集合。

二、创建集合

调用set(),传入list作为元素。

set(list)

三、访问集合

由于集合是无序的,所以我们不能直接使用索引来访问。

访问集合中的元素,可以转换为判断该元素是否存在于集合中的问题。

使用in操作符判断

s = set(['A', 'a', 'L', 'l', 'B', 'b', 'P', 'p'])
print 'a' in s  # true
print 'c' in s  # False

四、集合的特点

  • 可以包含一系列元素,这点和列表很像;
  • 元素不可重复,这点和字典的key很像;可以使用元素不可重复的特性,来做去重操作。
  • 必须是不变对象,这点也和字典的key很像;
  • 存储的元素无序;

实例:判断用户输出的月份是否有效?

months = set(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
x1 = 'Feb'
x2 = 'Sun'

if x1 in months:
    print 'x1: ok'
else:
    print 'x1: error'

if x2 in months:
    print 'x2: ok'
else:
    print 'x2: error'

五、遍历集合

s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
for x in s:
    print x[0],":",x[1]

六、更新集合

set存储的是一组不重复的无序元素。

更新主要是两件事情,添加新元素进入集合;从已有元素中删除元素。

添加元素,使用add()方法。如果集合中不存在该元素则添加进去,存在的话也不会报错;

删除元素,使用remove()方法。如果集合中存在元素则删除,不存在元素会报错。

>>> s = set([1,2,3,4,5])
>>> print s
set([1, 2, 3, 4, 5])
>>> s.add(6)
>>> print s
set([1, 2, 3, 4, 5, 6])
>>> s.add(6)
>>> print s
set([1, 2, 3, 4, 5, 6])
>>> s.remove(6)
>>> print s
set([1, 2, 3, 4, 5])
>>> s.remove(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 6
>>>


用add()可以直接添加,用remove()删除之前需要判断。

s = set(['Adam', 'Lisa', 'Paul'])
L = ['Adam', 'Lisa', 'Bart', 'Paul']
for i in L:
    if i in s:
        s.remove(i)
    else:
        s.add(i)
print s

本篇文档中代码是在python2.0下执行的~~如果大家要参考,记得在python2下执行哦~~

猜你喜欢

转载自blog.csdn.net/loner_fang/article/details/80858509