class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
"""
wjh=set(['','',''])
wjh.add('')
wjh.add('')
print(wjh)
{'', '', '', ''} set中元素是唯一的
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
wjh.add('') def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass
wjh.clear()清除set所有数据 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. (i.e. all elements that are in this set but not the others.)
"""
pass
取两个set合集差异,取单集合
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
delete_set=old_set.difference(new_set)
print(delete_set)
{'#2'} 只取了old_set中的差异 def difference_update(self, *args, **kwargs): # real signature unknown
""" 删除当前set中的所有包含在 new set 里的元素 """
""" Remove all elements of another set from this set. """
pass
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
delete_update_set=old_set.difference_update(new_set)
print(old_set)
{'#2'} 删除old_set中与new相重叠的元素 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
new = new_dict.keys()
new_set=set(new)
delt=new_set.discard('#3')
print(new_set)
{'#1', '#4'}移除特定元素 def intersection(self, *args, **kwargs): # real signature unknown
""" 取交集,新创建一个set """
"""
Return the intersection of two or more sets as a new set. (i.e. elements that are common to all of the sets.)
"""
pass
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
new_jiaoji_set=new_set.intersection(old_set)
print(new_jiaoji_set)
{'#3', '#1'} def intersection_update(self, *args, **kwargs): # real signature unknown
""" 取交集,修改原来set """
""" Update a set with the intersection of itself and another. """
pass
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
new_jiaoji_set=new_set.intersection_update(old_set)
print(new_set)
{'#1', '#3'} def isdisjoint(self, *args, **kwargs): # real signature unknown
""" 如果没有交集,返回true """
""" Return True if two sets have a null intersection. """
pass
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
jieguo=new_set.isdisjoint(old_set)
print(jieguo)
False 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
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
pp=old_set.pop()
print(pp)
print(old_set)
#
{'#1', '#3'}
随机移除一个元素 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
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
#print(old_set)
pp=old_set.remove('#3')
print(pp)
print(old_set)
{'#1', '#2'} 移除一个指定元素 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
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
cha=old_set.symmetric_difference(new_set)
print(cha)
{'#4', '#2'} def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" 差集,改变原来 """
""" Update a set with the symmetric difference of itself and another. """
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
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
unic=old_set.union(new_set)
print(unic)
{'#3', '#1', '#4', '#2'} 合并 def update(self, *args, **kwargs): # real signature unknown
""" 更新 """
""" Update a set with the union of itself and others. """
pass
old = old_dict.keys()
new = new_dict.keys()
old_set=set(old)
new_set=set(new)
update=old_set.update(new_set)
print(old_set)
{'#1', '#2', '#4', '#3'} 更新 def __and__(self, y): # real signature unknown; restored from __doc__
""" x.__and__(y) <==> x&y """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __iand__(self, y): # real signature unknown; restored from __doc__
""" x.__iand__(y) <==> x&=y """
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, y): # real signature unknown; restored from __doc__
""" x.__ior__(y) <==> x|=y """
pass def __isub__(self, y): # real signature unknown; restored from __doc__
""" x.__isub__(y) <==> x-=y """
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __ixor__(self, y): # real signature unknown; restored from __doc__
""" x.__ixor__(y) <==> x^=y """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __or__(self, y): # real signature unknown; restored from __doc__
""" x.__or__(y) <==> x|y """
pass def __rand__(self, y): # real signature unknown; restored from __doc__
""" x.__rand__(y) <==> y&x """
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __ror__(self, y): # real signature unknown; restored from __doc__
""" x.__ror__(y) <==> y|x """
pass def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass def __rxor__(self, y): # real signature unknown; restored from __doc__
""" x.__rxor__(y) <==> y^x """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass def __xor__(self, y): # real signature unknown; restored from __doc__
""" x.__xor__(y) <==> x^y """
pass __hash__ = None
set集合
set集合
set是一个无序且不重复的元素集合 练习:寻找差异
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 # 数据库中原有
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':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 }
} 需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
copy(深浅拷贝)
import copy
字符串,整数,浮点,列表,元组(深浅拷贝都一样)
'''
a1 = 1223444
a2 = a1
print(id(a1))
print(id(a2))
'''
a1 = 123444
'''
a2 = copy.copy(a1)
print(id(a1))
print(id(a2))
'''
'''
a2=copy.deepcopy(a1)
print(id(a1))
print(id(a2))
'''
当出现下面这种情况,包涵多个子值时,浅拷贝只会拷贝第一层的内存地址,而深拷贝则会拷贝除最后一层外所有。 n1 = {'k1':'v1','k2':'v2','k3':['wjh',223,]}
'''
print(id(n1))
n2 = n1
print(id(n2))
'''
监控模板调用例子:
#n2 = copy.copy(n1)
n2 = copy.deepcopy(n1)
#print(id(n1['k3']))
#print(id(n2['k3'])) dic = {
'cpu':[80,],
'mem':[80,],
'disk':[80,],
}
#print(dic)
new_dic=copy.deepcopy(dic)
#print(new_dic)
new_dic['cpu'][0] = 50
print(dic)
print(new_dic)
python之函数详解
返回值: import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def mail(user):
ret = True
try:
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
msg['To'] = formataddr(["走人",'133130355@qq.com'])
msg['Subject'] = "主题" server = smtplib.SMTP("smtp.126.com", 25)
server.login("wptawy@126.com", "WW.3945.59")
server.sendmail('wptawy@126.com', [user,], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
ret = mail('hdwangjianhui@163.com')
if ret:
print('success')
else:
print('shibai') 无参数:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def mail():
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
msg['To'] = formataddr(["走人",'424662508@qq.com'])
msg['Subject'] = "主题" server = smtplib.SMTP("smtp.126.com", 25)
server.login("wptawy@126.com", "邮箱密码")
server.sendmail('wptawy@126.com', ['133130355@qq.com',], msg.as_string())
server.quit()
mail()
普通参数: import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def mail(user):
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
msg['To'] = formataddr(["走人",'424662508@qq.com'])
msg['Subject'] = "主题" server = smtplib.SMTP("smtp.126.com", 25)
server.login("wptawy@126.com", "邮箱密码")
server.sendmail('wptawy@126.com', [user,], msg.as_string())
server.quit()
mail('133130355@qq.com')
默认参数: def func(name, age = 18): print ("%s:%s" %(name,age)) # 指定参数
func('wupeiqi', 19)
# 使用默认参数 func('alex') 动态参数:
* def pr(*args):
print(args)
wjh=['1','2']
pr(wjh)
*可以传递元组,字符,列表 **
def pr(**args):
print(args)
pr(wjh={'wjh':'123',})
**可以传递字典 def pr(*args,**kwargs):
print(args)
print(kwargs)
pr([1,2,3,4],wjh={'wjh':'123',})
当两个参数都存在时一定要先写*的
双向队列:
可以将值从左右提取插入。 import collections d = collections.deque()
d.append('1')
d.appendleft('10')
d.appendleft('1')
print(d)
print(d.count('1'))
d.extend(['y','yy','n'])#扩展
d.extendleft(['t','1'])
d.rotate(1) #将最后一个值放到第一个 单向队列:
只能将值从左到右传入,取出,(类似子弹夹原理) import queue
#qsize:查看队列元素个数
#empty:清除
#full:是否填满
#put:插入数据
#get:取数据
q = queue.Queue()
q.put('123')
q.put('456')
print(q.qsize())
print (q.get())
字典(扩展)
有序字典: import collections
dic = collections.OrderedDict()
dic['a'] = 'a1'
dic['b'] = 'b1'
dic['c'] = 'c1'
print(dic)
通过列表去像字典传输元素,以达到有顺序。 默认字典: dic = collections.defaultdict(list)定义默认字典的元素为list。
#dic={}
a = [11,22,33,44,55,66,77,88,99]
for i in a:
if i >66:
dic['k1'].append(i)
else:
dic['v2'].append(i) 可命名元组:
print(dic)name_tuple=collections.namedtuple('name_tuple',['x','y','z'])
tuple1=name_tuple(11,22,33)
print(tuple1.x)
print(tuple1.y)
内置函数
查看详细:https://docs.python.org/3/library/functions.html#next
abs()绝对值 all()当所有值为真才为真:None,Flase,空,都为假 a=all(['1',])
print(a) True any()当其中值任意一个为真就为真。 bin()查看整数二进制 bool()查看布尔类型:Ture/Flase chr()将整数转换为计算机识别的字符: a = chr(81)
print(a) Q 可用于验证码 ord()将字符转换为数字: a = ord('A')
print(a) 65 random:生成随机数。
import random
print(random.randint(1,99)) dict():生成字典。
dir():查看对象可以使用的操作。 a = dir(111)
print(a)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] divmod:整除并且返回余数。 enumerate:将目标加上序号。 wjh={
'wjh1':'11',
'wjh2':'22',
}
for i,v in enumerate(wjh,2):
print(i,v)
2 wjh2
3 wjh1 eval():函数将字符串str当成有效Python表达式来求值,并返回计算结果。
r = 1
print eval()
r =1
print (eval('r + 1')) float():浮点数。
help():帮助。
id():查看内存地址。
input():插入。
int():整数。
hex():16进制转换。
len():长度。
list():列表
min():最小值
max():最大值
oct():八进制
open():打开文件
print():打印
pow():次方 import math
a = pow(2,2)
print(a) range():定义数量
reversed():反转
set():定义唯一集合
round():大约,约等于
sorted():排序
str():字符串
sum():求和
tuple():元组
type():类型
vars():查看内置方法 class a:
foo=100
b = vars(a)
print(b) zip():将数组进行组合成列表。
map():map函数会根据提供的函数对指定序列做映射。 lil=[22,23,24,]
new_li=map(lambda x:x + 100,lil)
li = list(new_li)
print(li) filter():过滤 li1=[11,22,33,44]
def fuc(x):
if x>22:
return True
else:
return False
new_li=filter(fuc,li1)
print(list(new_li))
lambda表达式
学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:
# 普通条件语句
if 1 == 1:
name = 'wupeiqi'
else:
name = 'alex' # 三元运算
name = 'wupeiqi' if 1 == 1 else 'alex' 对于简单的函数,也存在一种简便的表示方式,即:lambda表达式 # ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):
return arg + 1 # 执行函数
result = func(123) # ###################### lambda ###################### # 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1 # 执行函数
result = my_lambda(123) lambda存在意义就是对简单函数的简洁表示
文件操作
open函数,该函数用于文件处理
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
一、打开文件
1
|
文件句柄 = open ( '文件路径' , '模式' )
|
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
- 二、操作
复制代码 class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 好文要顶 关注我 收藏该文