zoukankan      html  css  js  c++  java
  • Python 学习笔记(十)Python集合(一)

    回顾

    int/float/str/list/tuple/dict

    整数型和浮点型是不可变的,不是序列

    字符串是不可变的,是序列

    列表是可变的,是序列

    元组是不可变的,是序列

    字典是可变得,但不是序列

    集合的基本概念

    集合是基本的数学概念,它是集合论的研究对象,指具有某种特定性质的事物的总体,(在最原始的集合论─朴素集合论─中的定义,集合就是“一堆东西”。)集合里的事物(“东西”),叫作元素。若然 x 是集合 A 的元素,记作 x ∈ A。

    创建集合的方法

    方法1:使用花括号{} ;用花括号所包裹的对象,就是一个集合

    方法2:set()函数 一般使用这个函数创建集合

    集合的元素没有顺序,不可重复

    集合是不可哈希的

     1 >>> {1,"python"} #使用花括号创建集合
     2 set(['python', 1])
     3 >>> type({1,"python"})
     4 <type 'set'>
     5 >>> set("python")
     6 set(['h', 'o', 'n', 'p', 't', 'y'])
     7 >>> s= set("python") #使用set()创建集合
     8 >>> s
     9 set(['h', 'o', 'n', 'p', 't', 'y'])
    10 >>> s2=set(["baidu","google","ali"])
    11 >>> type(s2)
    12 <type 'set'>
    13 >>> s2
    14 set(['baidu', 'google', 'ali']) #集合的元素没有顺序
    15 >>> s3=set([2,2,2,2,2]) 
    16 >>> s3  #集合元素不可重复
    17 set([2])
    18 >>>

    可哈希与不可哈希

    就是在其生存期内,不可变的对象,是可哈希的,反之,可变的就是不可哈希的

    Python中所有不可变的都是可哈希的,如数字、字符串、元组

    另列表、字典都是可变的,都是不可哈希的

    在字典中的Key键必须是可哈希的,即不可变的对象

    在集合中,集合的元素必须是可哈希的,也就是说集合的元素必须是不可变对象

    所以说用列表作为集合的元素,就报错,因为列表是不可哈希的对象

     1 >>> lst =[[1,2,3],"python"]   #用列表作为参数,创建一个集合,报错list 是不可hash的
     2 >>> s =set(lst)
     3 Traceback (most recent call last):
     4   File "<stdin>", line 1, in <module>
     5 TypeError: unhashable type: 'list'
     6 >>> d={[1,2,3]:"python"}   #创建一个字典,key为列表,报错list 是不可hash的
     7 Traceback (most recent call last):
     8   File "<stdin>", line 1, in <module>
     9 TypeError: unhashable type: 'list'   #list 是不可哈希的
    10 >>>

    集合与列表之间的转换

     set() list() 

     1 >>> lst=[1,2,3]
     2 >>> s =set(lst)  #将列表转换成集合
     3 >>> s
     4 set([1, 2, 3])
     5 >>> lst2 =list(s) #将集合转换为列表
     6 >>> lst2
     7 [1, 2, 3]
     8 >>> a =[1,2,2,3,3,6,6,8,9,0,0] #去除列表中的重复项,可使用set()集合
     9 >>> s =set(a)
    10 >>> s
    11 set([0, 1, 2, 3, 6, 8, 9])
    12 >>> a =list(s) #去除重复后,再转换为列表list
    13 >>> a
    14 [0, 1, 2, 3, 6, 8, 9]
    15 >>> s
    16 set([0, 1, 2, 3, 6, 8, 9]) 
    17 >>> hash(s) #返回hash值,也可判断是否可哈希,报错不可哈希,否则返回hash值
    18 Traceback (most recent call last):
    19   File "<stdin>", line 1, in <module>
    20 TypeError: unhashable type: 'set'
    21 >>> hash(1)
    22 1

    创建不可变集合

    frozenset() 创建不可变集合,是可哈希的

    1 >>> a
    2 [0,1,2,3,6,8,9]
    3 >>> s2 =frozenset(a)
    4 >>> type(s2)
    5 <type 'frozenset'>
    6 >>> hash(s2)
    7 2096340863
    8 >>>
  • 相关阅读:
    ini_set /ini_get函数功能-----PHP
    【转】那个什么都懂的家伙
    word 2007为不同页插入不同页眉页脚
    August 26th 2017 Week 34th Saturday
    【2017-11-08】Linux与openCV:opencv版本查看及库文件位置等
    August 25th 2017 Week 34th Friday
    August 24th 2017 Week 34th Thursday
    August 23rd 2017 Week 34th Wednesday
    August 22nd 2017 Week 34th Tuesday
    August 21st 2017 Week 34th Monday
  • 原文地址:https://www.cnblogs.com/wangruihua-521/p/8556057.html
Copyright © 2011-2022 走看看