python 数据类型

int, float, bool, string, tuple, list, dict, set

python基本数据类型之集合set

set集合,是一个无序且不重复的元素集合, set 类型同其他基本类型一样,也是一个类(class set(object)), 比如int(class int(object))

 

set也有如下特性:

  1. 不重复

  2. 元素为不可变对象

  3. 集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作

s = set() #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典

set类型变量初始化有两种方式:

1.  传统方式, 像其他基本数据类型(int,string...),不用显性创建类对象的方式

s = {11,22,33,44} 

set([33, 11, 44, 22])

s = {'boy'}

set(['boy'])

s={'boy','girl'}

set(['boy', 'girl'])

2. 用创建类对象方式, 这个时候要注意,set构造函数只接受iterable参数,然后把参数中的每一个元素作为set的一个元素

>>> s=set(11,22,33,44)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 4
>>> s=set(11)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

>>> s=set('122344')
>>> s
set(['1', '3', '2', '4'])

>>> s=set('11,22')
>>> s
set(['1', '2', ','])

复制代码
#set是一个无序且不重复的元素集合
>>> s1=set()
>>> s1
set([])

  >>> s1.add('alex')
  >>> s1
  set(['alex'])
  >>> s1.add("eric")
  >>> s1
  set(['alex', 'eric'])
  >>>

 

>>> a = {'boy'}         #等价于  a=set(['boy'])
>>> print(a, type(a))
(set(['boy']), <type 'set'>)

>>> b=set('boy')                 #
>>> print(b, type(b))
(set(['y', 'b', 'o']), <type 'set'>)

>>> b=set(['boy'])               #list
>>> print(b, type(b))
(set(['boy']), <type 'set'>)
>>>

>>> b=set(['y','b','o','o'])      #list
>>> print(b, type(b))
(set(['y', 'b', 'o']), <type 'set'>)

>>> c=set({"k1":'v1', 'k2':'v2'}) # dict
>>> print(c, type(c))
(set(['k2', 'k1']), <type 'set'>)

>>> d={'k1', 'k2', 'k2'}     #string
>>> print(d, type(d))
(set(['k2', 'k1']), <type 'set'>)

>>> e={('k1','k2','k2')}   # tuple
>>> print(e,type(e))
(set([('k1', 'k2', 'k2')]), <type 'set'>)

>>> e=set(('k1','k2','k2'))
>>> e
set(['k2', 'k1'])

#访问速度快
#天生解决了重复问题
ll=[1,2,3,4,5,6,3,2,1]
s2=set(ll)
print("转换后的集合为:",s2)
set([1, 2, 3, 4, 5, 6]) #去除相同项,生成一个新的集合,删除 s3=s2.difference([1,2,3,11]) print("s2不变:",s2) print("观察是否生成一个新的集合s3:",s3)
set([4, 5, 6]) s4=s2.difference_update([3,4,5,11]) #删除所有包含在新集合中的元素,并生成一个新的集合 print("是否改变原集合s2:",s2)
set([1, 2, 6]) print("是否生成新集合s4:",s4)
ret=s2.pop() #取出元素,并赋值给ret print("移除s2中的一个元素",s2) print("测试pop是否有返回值,移除的元素是:",ret) ret1=s2.remove(2) #必须带参数且没有返回值 print("移除s2中的一个元素:",s2) print("测试remove是否有返回值:",ret1) #练习 # 数据库中原有 old_dict = { "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 }, "#2":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 }, "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 } } # cmdb 新汇报的数据 new_dict = { "#1":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 800 }, "#3":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 }, "#4":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 } } """ 分析: 1、新有,原来无→新加入 2、新有,原来有→更新 3、新无,原来有→原来删除 使用set的交集和差集来计算 old_dict.keys() new_dict.keys() 交集(更新):要更新的数据 差集(删除):old_dict.keys()--交集 差集(添加):new_dict.keys()--交集 """ old=set(old_dict.keys()) new=set(new_dict.keys()) up_set=old.intersection(new) #需要更新的集合 del_set=old.symmetric_difference(up_set) #需要删除的集合 add_set=new.symmetric_difference(up_set) #需要添加的集合
复制代码

比较元素-->difference()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#set1中有而set2中没有的值
ret = set1.difference(set2)
print(ret)

删除两集合中相同的元素-->difference_update()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#从set1中删除和set2中相同的元素
set1.difference_update(set2)
print(set1)
print(set2)

移除元素-->discard(values)

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#移除指定元素,不存在不会报错,remove()不存在会报错,建议discard
set1.discard(44)
print(set1)

取交集值-->intersection()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#取两个set集合的交集值
ret = set1.intersection(set2)
print(ret)

取交集并更新-->intersection_update()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#取交集并更新到set1中
set1.intersection_update(set2)
print(set1)

对称交集-->symmetric_difference()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#对称交集,取两个集合中互不存在的元素,生成一个新的集合
ret = set1.symmetric_difference(set2)
print(ret)

对称交集并更新-->symmetric_difference_update()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#对称交集,并更新元素到set1中
set1.symmetric_difference_update(set2)
print(set1)

并集-->union()

set1 = {1,44,87,23,55}
set2 = {1,44,88,23,67}
#并集并更新到新的集合中
ret = set1.union(set2)
print(ret)

 

二、创建


s = set()
s = {11,22,33,44}  #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典

a=set('boy')
b=set(['y', 'b', 'o','o'])
c=set({"k1":'v1','k2':'v2'})
d={'k1','k2','k2'}
e={('k1', 'k2','k2')}
print(a,type(a))
print(b,type(b))
print(c,type(c))
print(d,type(d))
print(e,type(e))

OUTPUT:
{'o', 'b', 'y'} <class 'set'>
{'o', 'b', 'y'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{('k1', 'k2', 'k2')} <class 'set'>

三、基本操作

比较


se = {11, 22, 33}
be = {22, 55}
temp1 = se.difference(be)        #找到se中存在,be中不存在的集合,返回新值
print(temp1)        #{33, 11}
print(se)        #{33, 11, 22}

temp2 = se.difference_update(be) #找到se中存在,be中不存在的集合,覆盖掉se
print(temp2)        #None
print(se)           #{33, 11},

删除

discard()、remove()、pop()


se = {11, 22, 33}
se.discard(11)
se.discard(44)  # 移除不存的元素不会报错
print(se)

se = {11, 22, 33}
se.remove(11)
se.remove(44)  # 移除不存的元素会报错
print(se)

se = {11, 22, 33}  # 移除末尾元素并把移除的元素赋给新值
temp = se.pop()
print(temp)  # 33
print(se) # {11, 22}

取交集


se = {11, 22, 33}
be = {22, 55}

temp1 = se.intersection(be)             #取交集,赋给新值
print(temp1)  # 22
print(se)  # {11, 22, 33}

temp2 = se.intersection_update(be)      #取交集并更新自己
print(temp2)  # None
print(se)  # 22

判断


se = {11, 22, 33}
be = {22}

print(se.isdisjoint(be))        #False,判断是否不存在交集(有交集False,无交集True)
print(se.issubset(be))          #False,判断se是否是be的子集合
print(se.issuperset(be))        #True,判断se是否是be的父集合

合并


se = {11, 22, 33}
be = {22}

temp1 = se.symmetric_difference(be)  # 合并不同项,并赋新值
print(temp1)    #{33, 11}
print(se)       #{33, 11, 22}

temp2 = se.symmetric_difference_update(be)  # 合并不同项,并更新自己
print(temp2)    #None
print(se)             #{33, 11}

取并集


se = {11, 22, 33}
be = {22,44,55}

temp=se.union(be)   #取并集,并赋新值
print(se)       #{33, 11, 22}
print(temp)     #{33, 22, 55, 11, 44}

更新


se = {11, 22, 33}
be = {22,44,55}

se.update(be)  # 把se和be合并,得出的值覆盖se
print(se)
se.update([66, 77])  # 可增加迭代项
print(se)

集合的转换


se = set(range(4))
li = list(se)
tu = tuple(se)
st = str(se)
print(li,type(li))
print(tu,type(tu))
print(st,type(st))

OUTPUT:
[0, 1, 2, 3] <class 'list'>
(0, 1, 2, 3) <class 'tuple'>
{0, 1, 2, 3} <class 'str'>

四、源码


class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): 
        """添加"""
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass

    def clear(self, *args, **kwargs): 
        """清除"""
        """ Remove all elements from this set. """
        pass

    def copy(self, *args, **kwargs): 
        """浅拷贝"""
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs): 
        """比较"""
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)
        """
        pass

    def difference_update(self, *args, **kwargs): 
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): 
        """删除"""
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.
        """
        pass

    def intersection(self, *args, **kwargs): 
        """
        Return the intersection of two sets as a new set.
        
        (i.e. all elements that are in both sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): 
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): 
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): 
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs): 
        """ Report whether this set contains another set. """
        pass

    def pop(self, *args, **kwargs): 
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

    def remove(self, *args, **kwargs): 
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.
        """
        pass

    def symmetric_difference(self, *args, **kwargs): 
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

    def symmetric_difference_update(self, *args, **kwargs): 
        """ Update a set with the symmetric difference of itself and another. """
        pass

    def union(self, *args, **kwargs): 
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)
        """
        pass

    def update(self, *args, **kwargs): 
        """ Update a set with the union of itself and others. """
        pass

    def __and__(self, *args, **kwargs): 
        """ Return self&value. """
        pass

    def __contains__(self, y): 
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, *args, **kwargs): 
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): 
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs): 
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): 
        """ Return self>value. """
        pass

    def __iand__(self, *args, **kwargs): 
        """ Return self&=value. """
        pass

    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        
        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs): 
        """ Return self|=value. """
        pass

    def __isub__(self, *args, **kwargs): 
        """ Return self-=value. """
        pass

    def __iter__(self, *args, **kwargs): 
        """ Implement iter(self). """
        pass

    def __ixor__(self, *args, **kwargs): 
        """ Return self^=value. """
        pass

    def __len__(self, *args, **kwargs): 
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): 
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): 
        """ Return self<value. """
        pass

    @staticmethod 
    def __new__(*args, **kwargs): 
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): 
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): 
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs): 
        """ Return value&self. """
        pass

    def __reduce__(self, *args, **kwargs): 
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs): 
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs): 
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs): 
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs): 
        """ Return value^self. """
        pass

    def __sizeof__(self): 
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, *args, **kwargs): 
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs): 
        """ Return self^value. """
        pass

    __hash__ = None
 

Python Class
 
1. 构造函数 __init__:
   python class只允许一个构造函数,如果你定义了多个构造函数, 最后一个会覆盖前面的,前面的构造函数是不会起作用的,比如:
   
class Node(object):
def __init__(self):
self.head = None

def __init__(self, data):
self.data = data
self.nex = None
if __name__ == '__main__':
li = Node()

这时运行会报错:
TypeError: __init__() takes exactly 2 arguments (1 given)
 
 
 
python 数据结构

单向链表

链表的定义:

  链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址。由于每个结点都包含了可以链接起来的地址信息,所以用一个变量就能够访问整个结点序列。也就是说,结点包含两部分信息:一部分用于存储数据元素的值,称为信息域;另一部分用于存储下一个数据元素地址的指针,称为指针域。链表中的第一个结点的地址存储在一个单独的结点中,称为头结点或首结点。链表中的最后一个结点没有后继元素,其指针域为空。  

如下图所示:

 

单链表的结构:

单链表的插入和删除示意图:

 
 

python实现代码:

复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-


class Node(object):
def __init__(self, val, p=0):
self.data = val
self.next = p


class LinkList(object):
def __init__(self):
self.head = 0

def __getitem__(self, key):
if self.is_empty():
print 'linklist is empty.'
return
elif key < 0 or key > self.getlength():
print 'the given key is error'
return
else:
return self.getitem(key)

def __setitem__(self, key, value):
if self.is_empty():
print 'linklist is empty.'
return
elif key < 0 or key > self.getlength():
print 'the given key is error'
return
else:
self.delete(key)
return self.insert(key)

def initlist(self, data):
self.head = Node(data[0])
p = self.head

for i in data[1:]:
node = Node(i)
p.next = node
p = p.next

def getlength(self):
p = self.head
length = 0
while p != 0:
length += 1
p = p.next

return length

def is_empty(self):
if self.getlength() == 0:
return True
else:
return False

def clear(self):
self.head = 0

def append(self, item):
q = Node(item)
if self.head == 0:
self.head = q
else:
p = self.head
while p.next != 0:
p = p.next
p.next = q

def getitem(self, index):
if self.is_empty():
print 'Linklist is empty.'
return
j = 0
p = self.head

while p.next != 0 and j < index:
p = p.next
j += 1

if j == index:
return p.data
else:
print 'target is not exist!'

def insert(self, index, item):
if self.is_empty() or index < 0 or index > self.getlength():
print 'Linklist is empty.'
return
if index == 0:
q = Node(item, self.head)
self.head = q

p = self.head
post = self.head
j = 0
while p.next != 0 and j < index:
post = p
p = p.next
j += 1

if index == j:
q = Node(item, p)
post.next = q
q.next = p

def delete(self, index):
if self.is_empty() or index < 0 or index > self.getlength():
print 'Linklist is empty.'
return

if index == 0:
q = self.head.next
self.head = q

p = self.head
post = self.head
j = 0
while p.next !=0 and j < index:
post = p
p = p.next
j += 1

if index == j:
post.next = p.next

def index(self, value):
if self.is_empty():
print 'Linklist is empty.'
return

p = self.head
i = 0
while p.next!=0 and not p.data == value:
p = p.next
i += 1

if p.data == value:
return i
else:
return -1


if __name__ == '__main__':
l = LinkList()
l.initlist([1, 2, 3, 4, 5])
print l.getitem(4)
l.append(6)
print l.getitem(5)

l.insert(4, 40)
print l.getitem(3)
print l.getitem(4)
print l.getitem(5)

l.delete(5)
print l.getitem(5)

l.index(5)
复制代码

结果:

5
6
4
40
5
6

posted @ 2018-01-08 19:43  alxe_yu  阅读(148)  评论(0)    收藏  举报