美文网首页
Python 基础知识全篇-集合(Sets)

Python 基础知识全篇-集合(Sets)

作者: BABYMISS | 来源:发表于2020-05-20 19:43 被阅读0次

    集合对象是一系列无序的,离散的哈希对象的集合。常用于成员测试,移除重复元素和一些算术运算例如交,并,差和对称差等。

    shapes = ['circle', 'square', 'triangle', 'circle']

    set_of_shapes = set(shapes)

    set_of_shapes

    shapes = {'circle', 'square', 'triangle', 'circle'}

    for shape in shapes:

        print(shape)

    set_of_shapes.add('polygon')

    print(set_of_shapes)

    存在性检查

    # Test if circle is IN the set (i.e. exist)

    print('Circle is in the set: ', ('circle' in set_of_shapes))

    print('Rhombus is in the set:', ('rhombus' in set_of_shapes))

    常用操作

    favourites_shapes = set(['circle','triangle','hexagon'])

    # Intersection

    set_of_shapes.intersection(favourites_shapes)

    # Union

    set_of_shapes.union(favourites_shapes)

    # Difference

    set_of_shapes.difference(favourites_shapes)

    相关文章

      网友评论

          本文标题:Python 基础知识全篇-集合(Sets)

          本文链接:https://www.haomeiwen.com/subject/gsxoohtx.html