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)

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)

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)

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

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

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)

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":""}
r = f5(dic)
print(r)
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":""}
f6(dic)
print(dic)

PYDay5- 数据类型set、三元运算、函数的更多相关文章

  1. JavaScript---js语法,数据类型及方法, 数组及方法,JSON对象及方法,日期Date及方法,正则及方法,数据类型转换,运算符, 控制流程(三元运算),函数(匿名函数,自调用函数)

    day46 一丶javascript介绍 JavaScript的基础分为三个       1.ECMAScript:JavaScript的语法标准.包括变量,表达式,运算符,函数,if语句,for语句 ...

  2. Python之路第三天,基础(3)-set,函数,内置函数,文件,三元运算,lambda

    set集合 集合是一个无序的,不重复的元素集合. 集合的创建: name_set = {'tom','jerry','alex','rose'} 或 name_set = set(['tom','je ...

  3. 第三天 函数 三元运算 lambda表达式 内置函数 文件操作

    面向过程: 直接一行一行写代码,遇到重复的内容复制黏贴. 不利于代码阅读 代码没有复用 面向对象 将代码块定义为函数,以后直接调用函数 增强了复用性 函数的定义方法 def 函数名(传递参数): 函数 ...

  4. bytes数据类型和字符串的编码解码,三元运算,进制互换

    三元运算 如果这个条件成立就存这个值,如果那个条件成立就存那个值. 进制 bytes类型,字节数据类型也就是二进制类型,这个是python3专有数据类型,在python2里跟字符串是一个类型,也就是p ...

  5. day4 内置函数 迭代器&生成器 yield总结 三元运算 闭包

    内置函数: 内置函数 # abs()返回一个数字的绝对值.如果给出复数,返回值就是该复数的模. b = -100 print(b) print(abs(b)) # all() 所有为真才为真,只要有一 ...

  6. python基础-3 集合 三元运算 深浅拷贝 函数 Python作用域

    上节课总结 1 运算符 in 字符串 判断  : “hello” in "asdasfhelloasdfsadf" 列表元素判断:"li" in ['li', ...

  7. python基础(三元运算+深浅拷贝+函数参数)

    三元运算 三元运算,又称三目运算,主要作用是减少代码量,是对简单的条件语句的缩写. 书写格式: result = 值1 if 条件 else 值2 即如果条件成立,则将值1赋给result变量,如果不 ...

  8. Python全栈之路3--set集合--三元运算--深浅拷贝--初识函数

    一.上节课的重点回顾: 1.类名加括号其实就是执行类的__init__方法: 2.int a.创建方式 n1 = 123 #根据int类创建了一个对象 n2 = int(123) #根据int类创建一 ...

  9. python_way,day3 集合、函数、三元运算、lambda、python的内置函数、字符转换、文件处理

    python_way,day3 一.集合 二.函数 三.三元运算 四.lambda 五.python的内置函数 六.字符转换 七.文件处理 一.集合: 1.集合的特性: 特性:无序,不重复的序列 如果 ...

  10. python 匿名函数与三元运算

    匿名函数 匿名函数就是不需要显示式的指定函数名 首先看一行代码: def calc(x,y): return x*y print(calc(2,3)) # 换成匿名函数 calc = lambda x ...

随机推荐

  1. KEIL_RTX资源介绍

    调度方法:时间片轮转. 参考文档:Keil参考手册和rtl.h(任务的每个.c文件都应包含此头文件)头文件这两个文档 1)事件管理:让一个进程等待一个事件,这个事件可以由其它进程和中断触发(只能在中断 ...

  2. Problem D. What a Beautiful Lake dp

    Problem D. What a Beautiful Lake Description Weiming Lake, also named "Un-named Lake", is ...

  3. Unity Shader入门精要学习笔记 - 第16章 Unity中的渲染优化技术

    转自冯乐乐的 <Unity Shader 入门精要> 移动平台的特点 为了尽可能一处那些隐藏的表面,减少overdraw(即一个像素被绘制多次),PowerVR芯片(通常用于ios设备和某 ...

  4. #82. 【UR #7】水题生成器

    链接:http://uoj.ac/problem/82 今天是世界水日,著名的水题资源专家蝈蝈大臣向世界宣布了他的一项新发明 —— 水题生成器. 每道题目都有一个正整数的难度值.水题生成器虽然强大但是 ...

  5. 如何在asp.net mvc中添加自定义的HTML辅助种方法

    很久没在博客园发表文章了,今天来总结一下如何在asp.net mvc中添加自定义的HTML辅助方法.我们现在设计这么一个目前,利用自定义的HTML方法来渲染一个普通的img标记.直接进入主题吧: 首先 ...

  6. 解析dynamic对象

    最近做一个项目,需要解析由JSon转换过来的dynamic对象,JSon的解析可以直接使用fastJSon,但是如果不知道具体对象的话,后续的取值总是需要重复性的解析dynamic对象,很是麻烦,后来 ...

  7. Spring Cloud Gateway VS Zuul 比较,怎么选择?

    Spring Cloud Gateway 是 Spring Cloud Finchley 版推出来的新组件,用来代替服务网关:Zuul. 那 Spring Cloud Gateway 和 Zuul 都 ...

  8. android 插件化框架speed-tools

    项目介绍: speed-tools 是一款基于代理模式的动态部署apk热更新框架.插件化开发框架: speed-tools这个名字主要指的快速迭代开发工具集的意思. 功能与特性: 1.支持Androi ...

  9. 你不知道的HTTP之首部字段一览

    一.HTTP/1.1 首部字段一览 HTTP 首部字段根据实际用途被分为以下 4 种类型: 1.通用首部字段:请求报文和响应报文两方都会使用的首部. 首部字段名 说明 Cache-Control 控制 ...

  10. 最新深度ghost win7系统下载

    深度技术ghost win7系统 64位快速安装版 V2016年2月,深度技术ghost win7 64位快速安装版在不影响大多数软件和硬件运行的前提下,已经尽可能关闭非必要服务,自动安装AMD/In ...