PYDay5- 数据类型set、三元运算、函数

1、set

set集合,是一个无序且不重复的元素集合

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): # real signature unknown
        """
        Add an element to a set,添加元素
         
        This has no effect if the element is already present.
        """
        pass
 
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. 清除内容"""
        pass
 
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. 浅拷贝  """
        pass
 
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set. A中存在,B中不存在
         
        (i.e. all elements that are in this set but not the others.)
        """
        pass
 
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
        pass
 
    def discard(self, *args, **kwargs): # real signature unknown
        """
        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): # real signature unknown
        """
        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): # real signature unknown
        """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
        pass
 
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
        pass
 
    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set.  是否是子序列"""
        pass
 
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. 是否是父序列"""
        pass
 
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty. 移除元素
        """
        pass
 
    def remove(self, *args, **kwargs): # real signature unknown
        """
        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): # real signature unknown
        """
        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): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
        pass
 
    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.  并集
         
        (i.e. all elements that are in either set.)
        """
        pass
 
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. 更新 """
        pass
常用方法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# se = {11,22,33,44}
# se.add(55)
# print(se)
# se.discard(66)
# #se.remove(66)
# print(se)
# bf = {21,22,23,25}
#
# #取se bf的交集
# ret1 = se.intersection(bf)
# #取交集并更新se
# se.intersection_update(bf)
#
# print(ret1)
# print(se)
#
# ret2 = se.issubset(bf)
# ret3 = se.issuperset(bf)
# print(ret2)
# print(ret3)
#
# bf.pop()
# print(bf)

se = {11,22,33,44}
be = {11,22,77,55}
r1 = se.difference(be)
r2 = be.difference(se)
print(r1)
print(r2)
ret = se.symmetric_difference(be)
print(ret)
# se.symmetric_difference_update(be)
# print(se)
ret = se.union(be)
print(ret)
print(se)
se.update([21])
print(se)
示例代码1

1.1习题:

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 }
}
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count'2'mem_capicity'800 },
    "#3":{ 'hostname':c1, 'cpu_count'2'mem_capicity'80 }
    "#4":{ 'hostname':c2, 'cpu_count'2'mem_capicity'80 }
}
#老字典key 相同的键值,将新字典key值更新到old,
#老字典中存在,新字典不存在的 将old中的值删除
目的:更新数据源
#!/usr/bin/env python
# -*- coding:utf-8 -*-
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 }
}
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
    "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}
old_keys = old_dict.keys()
new_keys = new_dict.keys()
old_set = set(old_keys)
new_set = set (new_keys)
del_set = old_set.difference(new_set)
add_set = new_set.difference(old_set)
update_set = old_set.intersection(new_set)
部分代码

 2、深浅拷贝

2.1  数字和字符串:深浅拷贝、赋值地址都是一样的

2.2 其他(列表、字典、元组):潜拷贝,只copy 第一层;深拷贝,除底层外 其他都拷贝

3、三目运算也叫三元运算:
eg: name = "Lee"  if 1 == 1 else "Alice"
4、字符串
字符串:本质上是c语言的字符数组,不可修改,不可插入。
list:相当于c语言的链表,记录上下元素的位置
5、函数
  功能模块,程序调用时直接使用函数名来调用,不用每次都写,实现程序的解耦,提高程序代码效率。
5.1 定义格式
def 函数名(形参)
  函数体
5.2 调用格式
函数名(实参)
5.3函数的注意事项:
5.3.1 函数返回值关键字为return,执行return后,函数跳出,不在执行后面的代码;没有return关键字,函数默认返回值None
5.3.2 函数调用时不加参数则按照顺利将实参赋值给函数形参,如需不按顺序传递参数,则在调用时采用“形参=实参”的形式实现
5.3.3 动态参数: * 表示元组,**表示字典,eg:def f(*args,**kwargs)
5.3.4 函数调用时f(li):将li作为整体传递给函数,f(*li):将li的元素一个一个的传递给函数
5.3.5 函数体修改全局变量,要使用关键字global
5.4内置函数:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def email():
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr
    ret = True
    try:
        msg = MIMEText('邮件内容 test mail 2017-1-27 09:16:14 2017年1月27日11:16:37 \n 2017年1月28日06:47:51', 'plain', 'utf-8')
        msg['From'] = formataddr(["john li", 'lynctest02@tasly.com'])
        msg['To'] = formataddr(["hi hi ", 'lynctest01@tasly.com'])
        msg['Subject'] = "主题2017年1月28日06:47:25"

        server = smtplib.SMTP("mail.tasly.com", 25)
        server.login("lynctest02", "邮箱密码")
        server.sendmail('lynctest02@tasly.com', ['lynctest01@tasly.com', ], msg.as_string())
        server.quit()
    except:
        ret = False
    return  ret
i1 =  email()
print(i1)
mail 函数示例

6、全局变量与局部变量

局部变量:小写,仅在代码块内生效
全局变量:大写,可以被函数修改,若需修改全局变量加关键字global

7、 try  except

try:
c1
except:
c2
#若c1执行错误,则执行c2

 

8、作业:

1、简述普通参数、指定参数、默认参数、动态参数的区别

A:参见5.3

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

def f1(arg):
    al_num = 0
    spance_num = 0
    digit_num = 0
    other_num = 0
    for i in arg:
        if i.isdigit():
            digit_num += 1
        elif i.isspace():
            spance_num += 1
        elif i.isalpha():
            al_num += 1
        else:
            other_num += 1
    return (al_num,spance_num,digit_num,other_num)
r = f1("11134 t  gfsfgf adf adfa dasf**")
print(r)
View Code

 

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

def obj_len(arg):
    #如果是字符串、元组、列表
    if isinstance(arg,str) or isinstance(arg,tuple):
        if len(arg)>5:
            return  True
        else:
            return  False
    else:
        return None

temp = {1:1,2:1}
ret = obj_len(temp)

print(ret)
View Code

4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

def has_space(args):
    ret = True
    for c in args:
        if c.isspace():
            ret =False
            break
    return  ret


result = has_space("1123asdfdf")
print(result)
View Code

5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

def f2(args):
    if len(args)>2:
        return args[0:2]
    else:
        return args
li = [12,34,56]
print(f2(li))
View Code

6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

def f4(arg):
    ret = []
    for i in range(len(arg)-1):
        if i % 2 == 1:
            ret.append(arg[i])
        else:
            pass
    return  ret

li = [11,22,33,44,55]
r = f4(li)
print(li)
print(r)
View Code

7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

dic = {"k1""v1v1""k2": [11,22,33,44]}
 
PS:字典中的value只能是字符串或列表
def f5(arg):
    ret ={}
    for k,v in arg.items():
        if len(v) > 2:
            ret[k] = v[0:2]
        else:
            ret[k] = v
    return  ret

dic = {"k1": "v1v1", "k2": [11, 22, 33, 44],"k3":"12"}
r = f5(dic)
print(r)
View Code
def f6(arg):
    for k,v in arg.items():
        if len(v) > 2:
            arg[k] = v[0:2]
        else:
            arg[k] = v

dic = {"k1": "v1v1", "k2": [11, 22, 33, 44],"k3":"12"}
f6(dic)
print(dic)
View Code

 

 

 

posted @ 2017-01-26 23:42  john221100  阅读(272)  评论(0编辑  收藏  举报