python中的set学习

来源:互联网 发布:网络授课老师招聘 编辑:程序博客网 时间:2024/05/22 03:21

集合是独立不同个体的无序集合。示例如下:

animals = {'cat', 'dog'}print 'cat' in animals   # Check if an element is in a set; prints "True"print 'fish' in animals  # prints "False"animals.add('fish')      # Add an element to a setprint 'fish' in animals  # Prints "True"print len(animals)       # Number of elements in a set; prints "3"animals.add('cat')       # Adding an element that is already in the set does nothingprint len(animals)       # Prints "3"animals.remove('cat')    # Remove an element from a setprint len(animals)       # Prints "2"

和前面一样,要知道更详细的,查看文档。

循环Loops:在集合中循环的语法和在列表中一样,但是集合是无序的,所以你在访问集合的元素的时候,不能做关于顺序的假设。

animals = {'cat', 'dog', 'fish'}for idx, animal in enumerate(animals):    print '#%d: %s' % (idx + 1, animal)# Prints "#1: fish", "#2: dog", "#3: cat"

集合推导Set comprehensions:和字典推导一样,可以很方便地构建集合:

from math import sqrtnums = {int(sqrt(x)) for x in range(30)}print nums  # Prints "set([0, 1, 2, 3, 4, 5])"
0 0
原创粉丝点击