zoukankan      html  css  js  c++  java
  • python之集合(set)学习

    集合(set)

    集合是一个无序的不重复元素序列,使用大括号({})、set()函数创建集合,

    注意:创建一个空集合必须用set()而不是{},因为{}是用来创建一个空字典。

      集合是无序的、不重复的、没有索引的

    1 a = {'hello','ni','hao','hi','ni','hao'}
    2 
    3 print(a)     # 输出结果没有重复项,且无序
    4 # print(a[1])   # TypeError: 'set' object does not support indexing

    输出结果:

    {'ni', 'hao', 'hello', 'hi'}

    添加集合元素

      添加单个元素:

    1 a = {'hello','ni','hao','hi','ni','hao'}
    2 print(a) 
    3 
    4 a.add('wo')
    5 print(a)
    6 
    7 a.add('hi')     # 如果元素已存在,则不进行任何操作。
    8 print(a)     

    输出结果:

    {'hi', 'ni', 'hao', 'hello'}
    {'hello', 'hi', 'wo', 'ni', 'hao'}
    {'hello', 'hi', 'wo', 'ni', 'hao'}

      添加多个元素、列表元素、字典元素

     1 a = {'hello','ni','hao','hi','ni','hao'}
     2 print(a)
     3 
     4 a.update("me", 'da')
     5 print(a)
     6 
     7 a.update({'user': 'name', 'pwd': 'mima'})
     8 print(a)
     9 
    10 print(len(a))
    11 a.update([1, 2, 3, 4])
    12 print(a)
    13 
    14 a.update(['abc', 'word', 'x'])
    15 print(a)

    输出结果:

    {'hi', 'hao', 'hello', 'ni'}
    {'hello', 'hao', 'e', 'ni', 'hi', 'd', 'a', 'm'}
    {'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}
    {1, 2, 3, 4, 'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}
    {1, 2, 3, 4, 'hello', 'abc', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'word', 'a', 'm', 'x'}

    输出结果有些出人意料,使用add添加单个元素时,不管该元素时单个字符还是字符串,都作为一个元素添加,而使用update则将字符串元素拆开为单个字符添加。

    而且添加的元素为字典时,可以发现,key值是按照字符串添加的,而value值也是拆开为单个字符添加。

    添加的元素为列表时,是将列表元素拆开,作为一个个单独的元素添加进集合,即使列表元素中有字符串,但是不在拆分该字符串。

    删除集合元素

      删除集合元素有三种方法:set.remove()、set.discard()、set.pop()

     1 a = {'hello','ni','hao','hi','ni','hao'}
     2 
     3 a.remove('hao')
     4 print(a)
     5 
     6 # a.remove('nihao')   # 如果元素不存在,会发生错误
     7 # print(a)
     8 a.discard('nihao')  # 如果元素不存在,不会发生错误
     9 print(a)
    10 
    11 a.pop()     # 随机删除集合中的一个元素,在交互模式中,删除集合中的第一个元素(排序后的第一个元素)
    12 print(a)

    输出结果:

    {'ni', 'hi', 'hello'}
    {'ni', 'hi', 'hello'}
    {'hi', 'hello'}

      清空集合元素:

    1 a = {'hello','ni','hao','hi','ni','hao'}
    2 
    3 a.clear()
    4 print(a)

    输出结果:

    set()

    遍历集合

      因为集合是无序的,所以不能使用索引,那么只能使用for循环来遍历。

    1 a = {'hello','ni','hao','hi','ni','hao'}
    2 
    3 for x in a:
    4     print(x)

    输出结果:

    hao
    ni
    hi
    hello

    学到这里,Python的基本数据类型已经简单的介绍完了,但是肯定不是这么点,还有更深更细节的知识就不是现阶段应该学的,那需要以后慢慢积累,多加练习才能掌握的。

    而且可以发现for循环好像十分强大,什么地方都可以使用for循环,那么为什么for循环这么强大呢?后面的文章将会谈到。

  • 相关阅读:
    COM编程入门
    DirectShow Filter 开发典型例子分析 ——字幕叠加 (FilterTitleOverlay)1
    互联网的三大巨头 百度 阿里巴巴 腾讯(BAT)
    入侵Tomcat服务器一次实战
    TinyXML:一个优秀的C++ XML解析器
    Apache POI (JAVA处理Office文档的类库)
    MediaInfo源代码分析 4:Inform()函数
    MediaInfo源代码分析 3:Open()函数
    洛谷 P3905 道路重建
    CF16A Flag
  • 原文地址:https://www.cnblogs.com/zuoxide/p/10514181.html
Copyright © 2011-2022 走看看